"Algorithms IV" for solving the Kosaraju algorithm of strong connected components
The Kosaraju algorithm (also known as the kosaraju–sharir algorithm ) is a linear time to find a An algorithm for strongly connected components in a forward graph .
The name of the mouthful came from his author, but he could not find his life. should be an Indian.
Solving problems: Requiring the number/division of strongly connected components in a forward graph
Algorithm steps:
That
For input g, invert the edges to obtain a reverse graph GR
The reversepost sequence is obtained by using the DFS algorithm to traverse the graph (after traversing the graph, push into a stack, and then the stack in reverse order)
DFS is performed on the Reversepost node in turn, and all nodes that Dfs accesses at a time are in a strong connectivity component.
When the graph is formed using adjacency table Form, the Kosaraju algorithm needs to complete two times the entire graph access, each access is proportional to the vertex number V and the number of edges E and v+e, so the access is completed in O (v+e).
Theorem used by the algorithm:
The inverse diagram of a graph has the same strong connected component as the original.
The indentation order of a graph's reversepost is its topological sort when and only if it is a DAG.
Code (in JAVA):
Kosarajuscc.java
Public classKOSARAJUSCC {Private Boolean[] marked;//reached vertices Private int[] ID;//Component Identifiers Private intCount//Number of strong components PublicKOSARAJUSCC (Digraph G) {marked=New Boolean[G.V ()]; ID=New int[G.V ()]; Depthfirstorder Order=NewDepthfirstorder (G.reverse ()); for(intS:order.reversepost ()) { if(!Marked[s]) {DFS (G, s); Count++; } } } Private voidDFS (Digraph G,intv) {Marked[v]=true; ID[V]=count; for(intW:g.adj (v))if(!Marked[w]) DFS (G, W); } Public BooleanStronglyconnected (intVintW) {returnID[V] = =Id[w]; } Public intIdintv) {returnId[v]; } Public intcount () {returncount; } Public Static voidMain (String args[]) {Scanner in=NewScanner (system.in); while(In.hasnext ()) {intN =In.nextint (); Digraph G=NewDigraph (N); intCIn.nextint (); for(inti = 0; i < E; i++) { intp =In.nextint (); intQ =In.nextint (); G.addedge (P, q); } KOSARAJUSCC KJ=NewKOSARAJUSCC (G); Log ("" +Kj.count ()); } } Private Static voidlog (String count2) {System.out.println (count2); }}
References
http://blog.csdn.net/dm_vincent/article/details/8554244
Https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/KosarajuSharirSCC.java.html
"Algorithms IV" for solving the Kosaraju algorithm of strong connected components