Kosaraju's algorithm

1 Summary

This is an algorithm to find strong connected components(SCC, from a vertex, it can reach to any vertex in this component) in a directed graph.

In a SCC, if you reverse every edge, it is still a SCC. For example,

  • v->u, u->v, v can reach to u and u can reach to v.
  • image all other intermediate nodes are negligible, you can see u->v as an edge
  • if you reverse all edges in this SCC, now you can get u->v, v->u.
  • so it is still a SCC.

2 pseudo code

KOSARAJU(G):

    stack = empty stack
    visited = array of false

    # Step 1: DFS on original graph
    for each vertex v in G:
        if visited[v] == false:
            DFS1(v)

    # Step 2: Reverse all edges
    GR = transpose(G)

    visited = array of false

    # Step 3: DFS on reversed graph
    while stack is not empty:
        v = stack.pop()

        if visited[v] == false:
            component = empty set
            DFS2(v)
            output component

 

3 Code

public class Kosaraju {

    public void dfs1 (int node, List<Integer> [] graph,
     boolean [] visited,
     ArrayDeque<Integer> stack) {
         visited[node] = true;
         for (int child : graph[node]) {
             if (!visited[child]) {
                 dfs1(child, graph, visited, stack);
             }
         }

         stack.push(node);
    }

    public void dfs2 (int node, List<Integer> [] reversedGraph,
     boolean [] visited,
     List<Integer> scc) {
         visited[node] = true;
         scc.add(node);
         for (int child : graph[node]) {
             if (!visited[child]) {
                 dfss(child, graph, visited, scc);
             }
         }
    }

    public List<List<Integer>> kosaraju (List<Integer> [] graph) {
        int n = graph.length;
        boolean [] visited = new boolean[n];
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            if (!visited[i]) dfs1(i, graph, visited, stack);
        }

        List<Integer> [] reversedGraph = new ArrayList[n];
        for (int i = 0; i < n; i++) reversedGraph[i] = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            for (int ch : graph[i]) {
                reversedGraph[ch].add(i);
            }
        }

        List<List<Integer>> sccs = new ArrayList<>();
        visited = new boolean[n];

        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                List<Integer> scc = new ArrayList<>();
                dfs2(i, reversedGraph, visited, scc);
                sccs.add(scc);
            }
        }
        return sccs;
    }
}

 

posted @ 2026-09-07 10:57  ylxn  阅读(4)  评论(0)    收藏  举报