Problem 584019 · medium · Level 05 Advanced Algorithms & Graphs

Counting the Islands of Mutual Reach

graphs · strongly connected components · Kosaraju

A strongly connected component is a largest set of nodes in which every node reaches every other. Every directed graph splits into such components; a node with no cycle through it forms one on its own.

Write scc_count(n, edges) returning how many there are.

Examples

Input:  n = 5, edges = [(0, 1), (1, 2), (2, 0), (3, 4)]
Output: 3
Explanation: the triangle 0-1-2, then 3 alone and 4 alone.

Input:  n = 1, edges = []
Output: 1

Constraints

  • 1 <= n <= 2 * 10**4, 0 <= len(edges) <= 10**5
  • Write the searches iteratively.

Goals

  • Group the nodes that can all reach one another
  • Order the first pass by finishing time and run the second on the reverse graph
  • Keep both passes iterative
Starting Python…