Directory
1 Problem Description
2 Solutions
2.1 based on the method of reduction and treatment
2.2 based on depth first lookup implementation
1 problem description
Given a forward graph, the topological sort sequence of this graph is obtained.
So, what is a topological sort?
definition: sorts the vertices in a forward graph in a linear fashion. That is, for any edge Uvs connected from the vertex u to the vertex V, the vertex U is always in front of the vertex v in the final sort result .
2 Solutions
2.1 based on the method of reduction and treatment
the principle of implementation: constantly do such a thing, in the remaining graph to find a source(PS: defined in the degree of 0 Vertex is the source of the graph, which is a vertex without an input edge, and then deletes it and all the edges from it. (If you have more than one of these sources, you can choose one.) If such a source does not exist, the algorithm stops, the problem is not solved at this time, the following gives the third edition of the Basic algorithm design and analysis of a map:
The specific code is as follows:
PackageCom.liuzhen.chapterFour;ImportJava.util.Stack; Public classtopologicalsorting {//Method 1: Based on the method of reduction: Look for the vertex with a degree of 0 in the graph as the vertex to be traversed, after traversing, delete this vertex /** parameter Adjmatrix: gives the adjacency matrix value of the graph * parameter source: gives the value of the number of each vertex of the graph * The function function: Returns the topological sort sequence of the graph*/ Public Char[] Getsourcesort (int[] Adjmatrix,int[] source) { intlen = source.length;//give the number of vertices of a graph Char[] result =New Char[Len];//defines the final return path character array intCount = 0;//used to calculate the number of vertices currently traversed BooleanJudge =true; while(judge) { for(inti = 0;i < source.length;i++){ if(Source[i] = = 0) {//when the first-I vertex is in the 0 o'clock, traverse the vertexresult[count++] = (Char) (' a ' +i); Source[i]=-1;//represents an I vertex has been traversed for(intj = 0;j < adjmatrix[0].length;j++) {//looking for the vertex of the first I vertex if(Adjmatrix[i][j] = = 1) Source[j]-= 1;//entry of J vertices minus 1 } } } if(Count = =len) Judge=false; } returnresult; } /** parameter Adjmatrix: gives the adjacency matrix value of the graph * Function function: Returns the value of the entry for each vertex of the graph*/ Public int[] GetSource (int[] adjmatrix) { intLen = adjmatrix[0].length; int[] Source =New int[Len]; for(inti = 0;i < len;i++){ //If column I in the adjacency matrix contains M 1, then the node in the column contains M-in, i.e. source[i] = M intCount = 0; for(intj = 0;j < len;j++){ if(Adjmatrix[j][i] = = 1) Count++; } Source[i]=count; } returnsource; } Public Static voidMain (string[] args) {topologicalsorting test=Newtopologicalsorting (); int[] Adjmatrix = {{0,0,1,0,0},{0,0,1,0,0},{0,0,0,1,1},{0,0,0,0,1},{0,0,0,0,0}}; int[] Source =Test.getsource (Adjmatrix); System.out.println ("gives the entry value of all the nodes (in alphabetical order) of the graph:"); for(inti = 0;i < source.length;i++) System.out.print (Source[i]+ "\ T"); System.out.println (); Char[] result =Test.getsourcesort (Adjmatrix, source); System.out.println ("gives the topology sort result of the graph:"); for(inti = 0;i < result.length;i++) System.out.print (Result[i]+ "\ T"); }}
Operation Result:
gives the values of all the nodes in the graph (in alphabetical order):0 0 2 1 2 topological ordering results for graphs: a b c D e
2.2 based on depth first lookup implementation
Quoted from the Netizen blog for an explanation:
in addition to using the algorithms shown in 2.1 Above, topology sequencing can be accomplished with depth-first traversal. This time you need to use the stack structure to record the results of the topology ordering.
Also extracts a pseudo-code on Wikipedia:
L ← Empty list that'll contain the sorted nodes
S ← Set of all nodes with no outgoing edges
For each node n in S do
visit (N)
function Visit (node N)
if n has no been visited yet then
Mark N as visited
For each node m with a edgefrom m to Ndo
visit (m)
add N to L
The implementation of DFS is simpler and more intuitive, using recursive implementations. by using Dfs to sort the topology, you actually only need to add one line of code, the last line in the pseudocode above: add N to L.
It is important to note that the time to add vertices to the results list is when the visit method is about to exit .
The key here is to understand: the last line in the pseudo code above: add nto L, for this line of understanding is focused on the recursive algorithm execution sequence of understanding, the core of the recursive execution sequence consists of two points:1. Recursion is performed first, followed by backtracking;2. Follow the characteristics of the stack, advanced back out. here can refer to my other blog: algorithm Note _017: A discussion of recursive execution order (Java)
Here is a diagram from the third edition of the Fundamentals of algorithmic design and analysis:
The specific code is as follows:
PackageCom.liuzhen.chapterFour;ImportJava.util.Stack; Public classtopologicalsorting {//Method 2: Get the topology sort based on depth first lookup (DFS) Public intCount1 = 0; PublicStack<character>RESULT1; /** Adjmatrix is the adjacency matrix of the graph to be traversed * value is the basis on which the graph vertex to be traversed is used for traversal, 0 means not traversed, and non-0 represents has been traversed*/ Public voidDfsint[] Adjmatrix,int[] value) {RESULT1=NewStack<character>(); for(inti = 0;i < value.length;i++){ if(Value[i] = = 0) Dfsvisit (adjmatrix,value,i); } } /** Adjmatrix is the adjacency matrix of the graph to be traversed * value is the basis on which the graph vertices are to be traversed for traversal, 0 for non-traversal, and not 0 for traversed * number is the array subscript numbered in the adjacency matrix of the vertex currently being traversed*/ Public voidDfsvisit (int[] Adjmatrix,int[] Value,intNumber ) {Value[number]= ++count1;//assign the ++count1 to the array element that is currently traversing the vertex judgment value to 0, which means that it has been traversed for(inti = 0;i < value.length;i++){ if(Adjmatrix[number][i] = = 1 && value[i] = = 0)//When the adjacent vertex of the current vertex can walk and it is traversedDfsvisit (Adjmatrix,value,i);//perform recursion, walk the first vertex } Chartemp = (Char) (' a ' +Number ); Result1.push (temp); } Public Static voidMain (string[] args) {topologicalsorting test=Newtopologicalsorting (); int[] Adjmatrix = {{0,0,1,0,0},{0,0,1,0,0},{0,0,0,1,1},{0,0,0,0,1},{0,0,0,0,0}}; int[] Value =New int[5]; Test.dfs (Adjmatrix, value); System.out.println (); System.out.println ("Use the Dfs method to get the reverse order of the topological sort sequence:"); System.out.println (TEST.RESULT1); System.out.println ("Get a topological sort sequence using the Dfs method:"); while(!Test.result1.empty ()) System.out.print (Test.result1.pop ()+ "\ T"); }}
Operation Result:
Use the Dfs method to get the reverse order of the topological sort sequence: [E, D, C, a, b] Use the Dfs method to get a topological sort sequence: b a c d E
Resources:
1. The principle and implementation of topological sequencing
Algorithm note _023: Topology ordering (Java)