AlgoFrames

Count SCCs

Standard · Write code · about 15 min

Return the number of strongly connected components of a directed graph. Two nodes are in the same component when each can reach the other.

graph.n is the node count and graph.edges lists [u, v] pairs for edges u → v. Edges may repeat, and self-loops can appear.

Example 1

Input:

[{"n":6,"edges":[[0,1],[1,2],[2,0],[1,3],[3,4],[4,3],[4,5]],"directed":true}]

Output:

3

Nodes 0 1 2 share a cycle, 3 4 share a cycle, and 5 is alone.

Example 2

Input:

[{"n":4,"edges":[[0,1],[1,2],[2,3]],"directed":true}]

Output:

4

A path has no cycle, so every node is its own component.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ number of edges ≤ 300
  • 0 ≤ u, v < n

Learn the idea first: Strongly connected components: Kosaraju and Tarjan, a visual lesson.

More Strongly connected components: Kosaraju and Tarjan problems