algorithm@ strongly Connected Component

Source: Internet
Author: User

Strongly Connected components

A directed graph is strongly connected if there are a path between all pairs of vertices. a strongly connected component (SCC) of a directed graph is a maximal strongly connected subgraph. For example, there is 3 SCCs in the following graph.

We can find all strongly connected-in O (v+e) time using Kosaraju ' s algorithm. Following is detailed Kosaraju ' s algorithm.
1) Create an empty stack ' S ' and do DFS traversal of a graph. In DFS traversal, after calling recursive DFS for adjacent vertices of a vertex, push the vertex to stack. In the above graph, if we start DFS from Vertex 0, we get vertices in stack as 1, 2, 4, 3, 0.
2) Reverse directions of all arcs to obtain the transpose graph.
3) one by one pops a vertex from S and S is not empty. Let the popped vertex is ' V '. Take V as source and does DFS (call DFSUtil (v)). The DFS starting from V prints strongly connected component of V. In the above example, we process vertices on order 0, 3, 4, 2, 1 (one by one popped from stack).

How does this work ?
The above algorithm is DFS based. It does DFS the Times. Dfs of a graph produces a single tree if all vertices is reachable from the DFS starting point. Otherwise DFS produces a forest. So DFS of a graph with only one SCC always produces a tree. The important point to note was DFS may produce a tree or a forest when there was more than one SCCs depending upon the Cho Sen starting point. For example, in the above diagram, if we start DFS from vertices 0 or 1 or 2, we get a tree as output. And if we start from 3 or 4, we get a forest. To find and print all SCCs, we would want to start DFS from Vertex 4 (which are a sink vertex), then move to 3 which is sin K in the remaining set (set excluding 4) and finally any of the remaining vertices (0, 1, 2). So how does we find this sequence of picking vertices as starting points of DFS? Unfortunately, there is no direct-to-getting this sequence. However, if we do a DFS of the graph and store vertices according to their The finish times, we make sure thaT the finish time of a vertex that connects to other SCCs (other, it own SCC), 'll always be greater than finish Tim E of vertices in the other SCC (see this for proof). For example, in DFS of above example graph, finish time of 0 are always greater than 3 and 4 (irrespective of the sequence of vertices considered for DFS). and finish time of 3 is always greater than 4. DFS doesn ' t guarantee about other vertices, for example finish times of 1 and 2 could be smaller or greater than 3 and 4 dep Ending upon the sequence of vertices considered for DFS. So to use the This property, we do DFS traversal the complete graph and push every finished vertex to a stack. In stacks, 3 always appears after 4, and 0 appear after both 3 and 4.
In the next step, we reverse the graph. Consider the graph of SCCs. In the reversed graph, the edges, connect, and both components is reversed. So the SCC {0, 1, 2} becomes sink and the SCC {4} becomes source. As discussed above, in stack, we all have 0 before 3 and 4. So if we do a DFS of the reversed graph using sequence of vertices in stacks, we process vertices from sink to source (in R eversed graph). That's what we wanted to achieve and that's all needed to print SCCs one by one.

//Java implementation of Kosaraju ' s algorithm to print all SCCsImportJava.io.*;ImportJava.util.*;Importjava.util.LinkedList;//This class represents a directed graph using adjacency list//Representationclassgraph{Private intV//No. of vertices    PrivateLinkedlist<integer> adj[];//adjacency List//ConstructorGraph (intv) {v=v; Adj=NewLinkedlist[v];  for(inti=0; i<v; ++i) adj[i]=NewLinkedList (); }     //Function to add a edge into the graph    voidAddedge (intVintW) {Adj[v].add (w);} //A recursive function to print DFS starting from V    voidDFSUtil (intVBooleanvisited[]) {        //Mark The current node as visited and print itVISITED[V] =true; System.out.print (v+ " "); intN; //Recur for all the vertices adjacent to this vertexiterator<integer> i =Adj[v].iterator ();  while(I.hasnext ()) {n=I.next (); if(!Visited[n])        DFSUtil (n,visited); }    }     //Function that returns reverse (or transpose) of the This graphGraph Gettranspose () {graph G=NewGraph (V);  for(intv = 0; v < V; v++)        {            //Recur for all the vertices adjacent to this vertexiterator<integer> i =Adj[v].listiterator ();  while(I.hasnext ()) G.adj[i.next ()].add (v); }        returnG; }     voidFillorder (intVBooleanvisited[], stack stack) {        //Mark The current node as visited and print itVISITED[V] =true; //Recur for all the vertices adjacent to this vertexiterator<integer> i =Adj[v].iterator ();  while(I.hasnext ()) {intn =I.next (); if(!Visited[n]) Fillorder (n, visited, stack); }         //All vertices reachable from V is processed by now,//Push V to StackStack.push (NewInteger (v)); }     //The main function , that finds, and prints all strongly//Connected Components    voidPrintsccs () {Stack stack=NewStack (); //Mark all, vertices as not visited (for first DFS)        BooleanVisited[] =New Boolean[V];  for(inti = 0; i < V; i++) Visited[i]=false; //Fill vertices in stacks according to their finishing// Times         for(inti = 0; i < V; i++)            if(Visited[i] = =false) Fillorder (i, visited, stack); //Create a reversed graphGraph gr =Gettranspose (); //Mark all, vertices as not visited (for second DFS)         for(inti = 0; i < V; i++) Visited[i]=false; //Now process all vertices on order defined by Stack         while(Stack.empty () = =false)        {            //Pop a vertex from stack            intv = (int) Stack.pop (); //Print strongly connected component of the popped vertex            if(Visited[v] = =false) {gr.                DFSUtil (V, visited);            System.out.println (); }        }    }     //Driver Method     Public Static voidMain (String args[]) {//Create A graph given in the above diagramGraph g =NewGraph (5); G.addedge (1, 0); G.addedge (0, 2); G.addedge (2, 1); G.addedge (0, 3); G.addedge (3, 4); System.out.println ("Following is strongly connected" + "in given graph");    G.printsccs (); }}

Output:

Following is strongly connected components in given Graph0 1 234

Time Complexity: The above algorithm calls DFS, fins reverse of the graph and again calls DFS. DFS takes O (v+e) for a graph represented using adjacency list. Reversing a graph also takes O (v+e) time. For reversing the graph, we simple traverse all adjacency lists.

The above algorithm is asymptotically best algorithm, but there be other algorithms like Tarjan ' s algorithm and path-base D which has same time complexity but find SCCs using a single DFS. The Tarjan ' s algorithm is discussed in the following post.

Tarjan ' s algorithm to find strongly Connected components

Applications:
SCC algorithms can used as a first step in many graph algorithms this work is on strongly connected graph.
In social networks, a group of people is generally strongly connected (for example, students of a class or any other comm On place). Many people in these groups generally like some common pages or play common games. The SCC algorithms can be used to find such groups and suggest the commonly liked pages or games to the people in the Grou P who has not yet liked commonly liked a page or played a game.

[email protected] Strongly Connected Component

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.