In the blink of an eye is November's tail, this month wrote an article, taking advantage of the week of 6th, the topological sort of Java implementation of the side
</pre><p> Implementation Method </p><p></p><pre name= "code" class= "Java" >import java.util.Stack;
public class Toposortmethod {int[] sort (int graph[][]) {int[] sortedarray = null;
Constructs a stack to hold the node stack<integer> stack=new stack<integer> ();
When the node is in the degree of 0, put the stack int list[]=new int[graph.length];
int k=0; for (int i=0;i<graph.length;i++) {//graph[i][0]==0, which indicates an in degree of 0, can be placed on the stack if (graph[i][0]==0) {Stack.push (i)
;
List[k]=i;
k++;
}} int stacklen=stack.size ();
int graphlen=graph.length;
while (Stacklen<graphlen) {//remove stack top element int pop=stack.pop ();
Determine whether the point of the stack element points to the element in the degree minus 1 is 0, if 0, then put in the stack int[] element=graph[pop];
int elementlen=graph[pop].length; A for (int j=1;j<elementlen;j++) {/////out-of-stack element points to a node that is less than 0, put in the stack if (--graph[element[j]][0] ==0) {Stack.push (element[j
]);
stacklen++;
LIST[K]=ELEMENT[J];
k++;
}}} int listlen=list.length; for (int j=0;j<listlen;j++) {System.out.print (List[j]+ "--->");
} return Sortedarray;
}
}
Test it.
public class Toposortmain {
/**
* @param args */public
static void Main (string[] args) {
//TODO Auto -generated method Stub
//construct diagram, input data
int graph[][]={{0,2,4},{1},{2,3},{1,5},{1,2,5},{2,1}}; int graph[][]= {{0,1,2,3},{2},{1,1,4},{2,4},{3},{0,3,4}};
Sort the topology
Toposortmethod toposortmethod=new Toposortmethod ();
Int[] Sortedarray =toposortmethod.sort (graph);
}
}
Output Result:
0--->4--->2--->3--->5--->1--->