Strongly connected components

Video lessonComing soon

1 Junctions you can leave and come back to

A city has only one-way streets. Some junctions form a pocket: from any junction in it, we can drive to any other and back again.

Here is a city of eight junctions. An arrow u → v is a street from u to v.

01234567
Eight junctions and eleven one-way streets

The streets 2 → 3 → 4 → 2 make 2, 3 and 4 a pocket. A street leads from 3 to 0, but no street leads back.

A largest group of vertices in which every vertex can reach every other is a strongly connected component (SCC). Every vertex is in exactly one. A vertex that no path leads back to is an SCC on its own, like junction 7.

In an undirected graph, one road joins two groups into one component. A one-way street does not. Traffic goes from one group into the other, but nothing comes back.

012
Two-way roads: one component
012
1 → 2 is one-way: two SCCs

A DFS from every vertex would show who reaches whom. At 10⁵ vertices and 10⁵ edges, that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE). Kosaraju's algorithm needs only two searches.

2 Shrink each pocket to one vertex

Our city has four SCCs. We name them A to D: A is 2, 3 and 4, B is 5 and 6, C is 0 and 1, and D is 7 alone.

01234567
The four SCCs, one tint each
ABCD
Each SCC shrunk to one vertex

Now we shrink each SCC to one vertex, and keep one arrow for the streets between two SCCs. The street 4 → 5 becomes A → B, and 3 → 0 becomes A → C. Both 6 → 7 and 1 → 7 lead into D. The new graph is the condensation.

The condensation never has a cycle. A cycle such as A → C → A would let every junction in A reach every junction in C and come back. Then A and C would be one SCC, not two.

So the condensation is a DAG, and the tools of the topological sort lesson work on it. Every DAG has at least one source, with no arrow coming in, and at least one sink, with no arrow going out. Here A is the source, and D is the sink.

3 Start each search in a dead end

A DFS reaches everything it can, and that is often more than one SCC. From 5, the search finds 6, and then 7 through 6 → 7. It leaks out of B into D.

A search from a sink cannot leak. From 7, it finds 7 alone. If each search started in a sink of what is left, and marked what it found, each would collect exactly one SCC. But we do not know where the sinks are.

Kosaraju's algorithm finds them with two ideas:

  • Reverse every edge. This flips every one-way sign in the city. The SCCs stay the same, since a way there and back is still one after the flip. But every arrow of the condensation turns round, so the source A becomes a sink.
  • The last vertex to finish is in a source. In a DFS, the vertex that finishes last always sits in a source SCC. The next section shows why.

So the algorithm has three steps:

  1. Run DFS over the whole graph, and list the vertices in the order they finish.
  2. Reverse every edge.
  3. Go through the list from the end. From each vertex not yet taken, run DFS on the reversed graph. The vertices it reaches that are not yet taken form one SCC.

4 Pass 1: the order vertices finish

As in the topological sort lesson, a vertex finishes when its call returns. Pass 1 starts a DFS from 0, then from each vertex still unvisited. Each vertex tries its streets in the order they were given.

StartThe search walksFinished, in order
00 → 1 → 77, 1, 0
1already visited
22 → 3 → 4 → 5 → 66, 5, 4, 3, 2
3 to 7already visited
7011026354453627
order: 7 finished first, 2 last
0211273645546370
Above each junction: its index in order

The latest finish in each SCC is 7 in A, 4 in B, 2 in C and 0 in D. Every street between two SCCs runs from a larger one to a smaller one.

Why this always holds. Take a street from SCC X into SCC Y. The search enters one of them first:

  • X first. The search enters some vertex x of X. Its call returns only after everything it can reach has finished, and it can reach all of Y. So x finishes after all of Y.
  • Y first. From Y, the search cannot reach X, or X and Y would be one SCC. So all of Y finishes before the search even enters X.

Both cases happened above. The search entered C first, at 0, and could not get back to A. Later it entered A at 2, and B finished inside that search.

So the last vertex to finish, 2, sits in a source. If a street came into its SCC, the SCC it came from would hold a later finish.

5 Pass 2: flip the signs and collect

Now every street turns round. On the reversed streets, A is a sink: its streets lead only to each other. Pass 2 walks order from the end, so i starts at 7, and order[i] is 2. Each search follows the reversed streets and enters only vertices not yet taken.

In the steps, tinted vertices are taken, and bold streets are the ones the search follows. A ringed vertex was reached but was already taken.

Pass 2 on the reversed streets
01234567
Reversed streets
7011026354453627i
From 2: it finds 4 and 3. That is A

The same run as a table. comp numbers the SCCs in the order they are found:

iorder[i]Taken?The search findscomp
72no2, 4, 30 (A)
6, 53, 4yes
45no5, 61 (B)
36yes
20no0, 12 (C)
11yes
07no73 (D)

Each search stopped at the edge of its own SCC. Every reversed street out of it was a real street into it. Those came from SCCs with a later finish, and pass 2 had already taken them.

Pass 2 always hands out the SCCs in a topological order of the condensation. Here it is A, B, C, D.

6 Kosaraju's algorithm in code

The code builds both maps at once: adj for the streets and reversedAdj for the flipped ones. visit is pass 1 and adds each vertex to order as it finishes. assign is pass 2. It marks with comp itself, where -1 means not taken yet.

On our city it returns [2, 2, 0, 0, 0, 1, 1, 3]: junctions 2, 3 and 4 are in SCC 0, and junction 7 is in SCC 3. At the end, count is 4, the number of SCCs.

C++

Pass the graph by reference. visit and assign take every vector with &. Without it, each call copies the whole graph, and the marks made by one call never reach the next.

Make each list first. The first loop adds an empty list for every vertex, so adj.get(u) exists before the first street is added to it.

About 1,000 calls deep. By default, Python stops a recursion at about 1,000 nested calls with a RecursionError. A long chain of vertices goes far deeper. sys.setrecursionlimit raises the limit.

Closures. visit and assign are defined inside componentOf, so they read adj, order and comp without taking them as arguments.

Fill comp with -1. A new slice of int is all zeros, and 0 is a real SCC number, so a loop sets every entry to -1 first. visit and assign call themselves, so each is declared with var before it is assigned.

i32 for the SCC numbers. The vertices are usize, but comp holds -1 for not taken, so it is a Vec<i32>. order.iter().rev() walks the finish list from the end.

Make each list. new List<int>[n] is an array of n nulls, so the first loop gives each vertex its own list before the first Add.

Cost. Building the two maps reads each edge once. Each pass then enters every vertex once and follows every edge once. So Kosaraju's algorithm is O(V + E), a few hundred thousand steps at 10⁵ vertices and 10⁵ edges. The maps take O(V + E) space, and the arrays and the call stack take O(V).

Tarjan's algorithm finds the same SCCs in one DFS, with no reversed graph, using a number per vertex called the low-link. The next lesson, on bridges, builds low-links step by step. Tarjan's algorithm is also O(V + E), but Kosaraju's is easier to explain and to get right.

7 Mistakes and edge cases

  • Not reversing the edges. Pass 2 on the real streets starts at 2 and reaches all eight junctions: one SCC instead of four.
  • Walking order from the front. Pass 2 then starts at 7. On the reversed streets, 7 leads to 1 and 6, and from them to every junction. Again one SCC instead of four.
  • Clearing the marks between searches. The marks of earlier SCCs are what stop a search. Without them, the search from 5 follows the reversed street 5 → 4 into A and reports 5, 6, 4, 3 and 2 as one SCC.
  • Keeping pass 1's marks. If pass 2 reuses visited as it is, every vertex looks taken, and pass 2 finds nothing. Our code marks pass 2 in comp instead.
  • Self-loops and repeated streets. They change nothing. A vertex whose only street leads back to itself is still an SCC on its own.
  • Deep recursion. On a chain 0 → 1 → … → 99999, pass 1 goes 10⁵ calls deep. The call stack can overflow, and the program stops with a Runtime Error.

Pass 2 can use any search, even BFS, because only the set of vertices it reaches matters. Pass 1 needs the finish order, so it keeps its own stack, and for each vertex, how many of its streets it has tried:

for each start not visited:
    mark start, push start
    while the stack is not empty:
        v = the top of the stack
        if v has a street it has not tried:
            w = the end of that street; count it as tried
            if w is not visited: mark w, push w
        else:
            pop v, add v to order

A vertex is popped when its call would have returned, so this gives the same list: 7, 1, 0, 6, 5, 4, 3, 2.

8 When to look for SCCs

The sign is a directed graph and a question about vertices that reach each other both ways.

  • Counting the groups. The answer is the number of SCCs, count in our code.
  • Can every vertex reach every other? Only when the whole graph is one SCC. Two searches tell: a DFS from 0 reaches every vertex, and so does a DFS from 0 on the reversed graph.
  • A vertex that reaches all the others. One exists exactly when the condensation has a single source. Then the vertex that finished last in pass 1 is one, and one more DFS from it checks. In our city, 2, 3 and 4 each reach everything.
  • Cycles in the way. A topological order, or counting paths, needs a DAG. The condensation is one.
  • 2-SAT. Each true-or-false choice x becomes two vertices, x and not x, and each rule becomes edges. All the rules can hold exactly when no x shares an SCC with its not x.
When cycles get in the way on a directed graph, find the SCCs first and shrink them. What is left is always a DAG.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.