

 This page uses content from Wikipedia. The original article was at Graph. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)



Kosaraju's algorithm (also known as the Kosaraju–Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.


For this task consider the directed graph with these connections:

 0 -> 1
 1 -> 2
 2 -> 0
 3 -> 1,  3 -> 2,  3 -> 4
 4 -> 3,  4 -> 5
 5 -> 2,  5 -> 6
 6 -> 5
 7 -> 4, 7  -> 6, 7 -> 7

And report the kosaraju strongly connected component for each node.



References

 The article on Wikipedia.
const VISITED=0,ASSIGNED=1;
 
fcn visit(u,G,L){	// u is ((visited,assigned), (id,edges))
   u0:=u[0];
   if(u0[VISITED]) return();
   u0[VISITED]=True;
   foreach idx in (u[1][1,*]){ visit(G[idx],G,L) } // vist out-neighbours
   L.insert(0,u);	// prepend u to L
}
fcn assign(u,root,G){  // u as above, root is a list of strong components
   u0:=u[0];
   if(u0[ASSIGNED]) return();
   root.append(u[1][0]);
   u0[ASSIGNED]=True;
   uid:=u[1][0];
   foreach v in (G){  // traverse graph to find in-neighbours, fugly
      n,ins := v[1][0],v[1][1,*];
      if(ins.holds(uid)) assign(G[n],root,G); // assign in-neighbour
   } 
}
fcn kosaraju(graph){  // Use Tarjan's algorithm instead of this one
   // input: graph G = (V, Es)
   // output: set of strongly connected components (sets of vertices)
 
   // convert graph to ( (index,lowlink,onStack),(id,links)), ...)
   // sorted by id
   G:=List.createLong(graph.len(),0);
   foreach v in (graph){ G[v[0]]=T( List(False,False),v) }
 
   L:=List();
   foreach u in (G){ visit(u,G,L) }
 
   components:=List.createLong(graph.len(),List.copy,True);
   foreach u in (L){ assign(u,components[u[1][0]],G) }
   components=components.filter();
 
   println("List of strongly connected components:");
   foreach c in (components){ println(c.reverse().concat(",")) }
 
   return(components);
}