Advanced Graphs Special edges and paths
489. Strongly Connected Components (Kosaraju)
You are given a directed graph with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges
is an edge from vertex u to vertex v. An edge can be followed only in its own direction, from u to v.
A strongly connected component is a largest group of vertices in which every vertex can reach every other one by following edges. Every vertex belongs to exactly one component. A vertex with no path back to itself is a component on its own.
Return the number of strongly connected components in the graph.
Example 1
Input: n = 6
edges = [[0, 1],
[1, 2],
[2, 0],
[2, 3],
[3, 4],
[4, 3],
[4, 5]]
3Explanation: Vertices 0, 1 and 2 reach each other around the cycle 0 → 1 → 2 → 0. Vertices 3 and 4 have an edge each way. Nothing leads back from 3 to the cycle, or from 5 to anything, so the components are 0, 1, 2, then 3, 4, then 5 alone.
Example 2
Input: n = 4, edges = [[0, 1], [1, 2], [0, 2], [3, 2]]
4Explanation: No path returns to the vertex it started from. So no two vertices reach each other, and each vertex is a component on its own.
Example 3
Input: n = 3, edges = [[0, 0], [1, 2], [2, 1]]
2Explanation: The edge [0,0] joins vertex 0 to nothing else, so 0 is a component alone. Vertices 1 and 2 have an
edge each way and form the second component.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 1050 ≤ edges.length ≤ 105edges[i].length == 20 ≤ ui, vi < n- An edge can go from a vertex to itself, and the same edge can appear more than once.
Clarifying questions
What you would ask an interviewer before writing any code.