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 to , not to . Some SCC algorithms use -based indexing, so add if needed.
This runs in time and uses space.