4--topological ordering of algorithms

Source: Internet
Author: User

    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--->



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.