Graph Theory37 sections · 1633 units
Open in Course

Planets and Kingdoms - Implementation

(C++ code)

After running Kosaraju or Tarjan:

numKingdoms = 0
for v from 1 to n:
    numKingdoms = max(numKingdoms, scc[v])

print numKingdoms
for v from 1 to n:
    print scc[v]

Make sure your SCC IDs are numbered from 11 to kk, not 00 to k1k - 1. Some SCC algorithms use 00-based indexing, so add 11 if needed.

This runs in O(V+E)O(V + E) time and uses O(V)O(V) space.