Strongly Connected Components
Advanced · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
In a network of one-way links, a strongly connected component is a group where you can get from any member to any other and back. Finding them shows the tightly tangled clusters and lets you treat each knot as a single unit.
Practical use cases
- Web app: Pages that link in circles. An SEO tool maps which pages link to which. Groups of pages that all link to each other, but nothing flows out to the rest of the site, trap visitors and crawlers. Finding these groups shows where to add outgoing links.
- Web app: Follow graph communities. On a social app, follows are one-way, so a group of accounts that keep following each other round and round forms a tight circle. Finding these circles lets marketers target each cluster with its own content, since people inside a tight circle tend to share interests.
- Web app: Tangled modules in a code base. A developer dashboard shows which files import which. A group of files importing each other in a ring makes testing and loading painful, and this check lists exactly which files form the knot to refactor.
- System: Compilers and deadlock analysis. Compilers find groups of functions that call each other, and databases find sets of transactions waiting in a circle. Each knot can be treated as a single block, and the blocks themselves never loop, which makes the rest of the analysis far simpler to handle.
The story: One-Way Streets of Chowk Nagar
The town of Chowk Nagar had a strange problem: almost every street was one-way. Auto-rickshaw driver Raju complained, "I drove to the temple junction and could not find any road home!"
Mrs. Sharma's class made a map for a project. They asked: "Which places are mutually reachable? Starting from X, can you reach Y and return from Y to X?" The kids coloured each such group of places with its own colour.
Soon they saw a pattern. The market, the bus stand and the school formed a loop of roads, so they could all reach one another: one colour. The temple and the dairy pointed to each other: another colour. A lonely dead-end junction had its own colour. And the roads between colours were always one-way, never forming a loop (otherwise two colours would have merged into one).
Each such colour group is a strongly connected component (SCC): a maximal set of nodes in a directed graph where every node can reach every other. Squash each group into a single dot and the whole map becomes a simple one-way DAG.
How to spot this problem, and where you need it
Your links have a direction, and you need to find the groups where everything can reach everything else, to simplify the picture, find knots, or detect circular waiting.
Signs you need it
- Links are one-way, such as follows, imports, calls, hyperlinks, or "waits for".
- The problem says "mutually reachable", "groups that can return to where they started", or "tangled dependencies".
- A normal connected-components count treats everything as one group, hiding the real structure.
Where to use it in a project
- Code quality tools reporting circular imports or mutually calling classes.
- Link and follow analysis for SEO, communities and recommendation features.
The solution
Use a two-pass or one-pass DFS method: Kosaraju does DFS, flips every arrow, and does DFS again in a special order; Tarjan does a single DFS with numbering. Each group produced is one strongly connected component. After finding them, you can squash each group into one node and the result is a loop-free graph that is easy to order or analyse.
Payoff: Before: a 300-file project where nobody knows what is tangled. After: the tool lists 4 knots, one of 12 files, as clear refactoring targets.
Explain it like I am 8
You and your friends live in places connected by one-way slides. Some groups can slide to each other in a circle and always get back. Those groups are "strongly connected". Groups that can only slide forward and never return are separate.
How it works, step by step
- Work with a directed graph (arrows have a direction). Plain undirected graphs just use connected components.
- Two nodes are in the same SCC if each can reach the other.
- Every node belongs to exactly one SCC. A node with no loop through it forms an SCC of one.
- Replace each SCC by a single super-node. The result has no cycles, so it can be topologically sorted.
- To find them quickly use Kosaraju (two DFS passes) or Tarjan (one DFS with a stack). The simple code below checks reachability from every node, to make the idea concrete.
The code in four languages
PHP
<?php
// Everything reachable from $start (depth-first search)
function reach(array $adj, int $start): array {
$seen = [$start => true];
$stack = [$start];
while ($stack) {
$u = array_pop($stack);
foreach ($adj[$u] as $v) {
if (!isset($seen[$v])) { $seen[$v] = true; $stack[] = $v; }
}
}
return $seen;
}
// Simple (slow) way: i and j are together if each can reach the other
function components(int $n, array $edges): array {
$adj = array_fill(0, $n, []);
foreach ($edges as [$a, $b]) $adj[$a][] = $b;
$canReach = [];
for ($i = 0; $i < $n; $i++) $canReach[$i] = reach($adj, $i);
$placed = array_fill(0, $n, false);
$groups = [];
for ($i = 0; $i < $n; $i++) {
if ($placed[$i]) continue;
$group = [];
for ($j = 0; $j < $n; $j++) {
if (isset($canReach[$i][$j]) && isset($canReach[$j][$i])) { // there and back
$group[] = $j;
$placed[$j] = true;
}
}
$groups[] = $group;
}
return $groups;
}
// junctions 1..6 become 0..5
$roads = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,3],[4,5]];
echo json_encode(components(6, $roads)) . PHP_EOL;JavaScript
// Everything reachable from start (depth-first search)
function reach(adj, start) {
const seen = new Set([start]);
const stack = [start];
while (stack.length) {
const u = stack.pop();
for (const v of adj[u]) {
if (!seen.has(v)) { seen.add(v); stack.push(v); }
}
}
return seen;
}
// Simple (slow) way: i and j are together if each can reach the other
function components(n, edges) {
const adj = Array.from({ length: n }, () => []);
for (const [a, b] of edges) adj[a].push(b);
const canReach = [];
for (let i = 0; i < n; i++) canReach.push(reach(adj, i));
const placed = new Array(n).fill(false);
const groups = [];
for (let i = 0; i < n; i++) {
if (placed[i]) continue;
const group = [];
for (let j = 0; j < n; j++) {
if (canReach[i].has(j) && canReach[j].has(i)) { // there and back
group.push(j);
placed[j] = true;
}
}
groups.push(group);
}
return groups;
}
// junctions 1..6 become 0..5
const roads = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,3],[4,5]];
console.log(JSON.stringify(components(6, roads)));Java
import java.util.*;
public class Main {
// Everything reachable from start (depth-first search)
static Set<Integer> reach(List<List<Integer>> adj, int start) {
Set<Integer> seen = new HashSet<>(List.of(start));
Deque<Integer> stack = new ArrayDeque<>();
stack.push(start);
while (!stack.isEmpty()) {
int u = stack.pop();
for (int v : adj.get(u)) {
if (seen.add(v)) stack.push(v); // add returns false if v was already there
}
}
return seen;
}
// Simple (slow) way: i and j are together if each can reach the other
static List<List<Integer>> components(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) adj.get(e[0]).add(e[1]);
List<Set<Integer>> canReach = new ArrayList<>();
for (int i = 0; i < n; i++) canReach.add(reach(adj, i));
boolean[] placed = new boolean[n];
List<List<Integer>> groups = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (placed[i]) continue;
List<Integer> group = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (canReach.get(i).contains(j) && canReach.get(j).contains(i)) { // there and back
group.add(j);
placed[j] = true;
}
}
groups.add(group);
}
return groups;
}
public static void main(String[] args) {
// junctions 1..6 become 0..5
int[][] roads = {{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 3}, {4, 5}};
System.out.println(components(6, roads)); // [[0, 1, 2], [3, 4], [5]]
}
}Go
package main
import "fmt"
// reach returns everything reachable from start (depth-first search).
func reach(adj [][]int, start int) map[int]bool {
seen := map[int]bool{start: true}
stack := []int{start}
for len(stack) > 0 {
u := stack[len(stack)-1]
stack = stack[:len(stack)-1]
for _, v := range adj[u] {
if !seen[v] {
seen[v] = true
stack = append(stack, v)
}
}
}
return seen
}
// components is the simple (slow) way: i and j are together if each can reach the other.
func components(n int, edges [][2]int) [][]int {
adj := make([][]int, n)
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
}
canReach := make([]map[int]bool, n)
for i := 0; i < n; i++ {
canReach[i] = reach(adj, i)
}
placed := make([]bool, n)
var groups [][]int
for i := 0; i < n; i++ {
if placed[i] {
continue
}
var group []int
for j := 0; j < n; j++ {
if canReach[i][j] && canReach[j][i] { // there and back
group = append(group, j)
placed[j] = true
}
}
groups = append(groups, group)
}
return groups
}
func main() {
// junctions 1..6 become 0..5
roads := [][2]int{{0, 1}, {1, 2}, {2, 0}, {2, 3}, {3, 4}, {4, 3}, {4, 5}}
fmt.Println(components(6, roads)) // [[0 1 2] [3 4] [5]]
}Time: O(V × (V + E)) for this simple version; O(V + E) with Kosaraju or Tarjan · Extra space: O(V²). Checking reachability from every node is easy to understand but slow; the clever algorithms do it in a single pass.
Watch out for
- Mixing up connected and strongly connected. A can reach B is not enough; B must reach A too.
- Applying the idea to undirected graphs. There, simple connected components are the same thing and BFS or DFS is enough.
- Forgetting that a lonely node (or a node with only a self-loop) still counts as its own component.
Quick check
- When are two nodes in the same strongly connected component?
- They have the same number of edges
- One can reach the other
- They share an edge
- Each can reach the other
- If you squash every SCC into one node, what does the graph look like?
- A DAG (no cycles)
- A single node
- A graph full of cycles
- A node has arrows out of it but none coming back to it through any path. Its SCC is:
- Missing
- Everyone else
- Just itself