算法之4--拓扑排序

来源:互联网 发布:云校排课软件怎么用 编辑:程序博客网 时间:2024/06/07 03:26

    转眼已经是11月的尾巴了,这个月就写了一篇文章,趁着周六日的时间,把拓扑排序用java实现了一边

</pre><p>实现方法</p><p></p><pre name="code" class="java">import java.util.Stack;public class TopoSortMethod {int[] sort(int graph[][]){int[] sortedArray = null;//构造一个栈,用来存放节点Stack<Integer> stack=new Stack<Integer>();//当节点的入度为0的时候,放入栈中int list[]=new int[graph.length];int k=0;for(int i=0;i<graph.length;i++)    {//graph[i][0]==0,表示入度为0,可以放入栈中if(graph[i][0]==0){stack.push(i);list[k]=i;k++; }     }int stackLen=stack.size();int graphLen=graph.length;while(stackLen<graphLen){//取出栈顶元素int pop=stack.pop();//判断出栈元素指向的点的元素入度减去1后是否为0,如果为0,则放入栈中int[] element=graph[pop];int elementLen=graph[pop].length;for(int j=1;j<elementLen;j++){//出栈元素指向的节点的入度减去一为0后,放入栈中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;}}

测试一下

public class TopoSortMain {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub//先构造图,输入数据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}};//进行拓扑排序TopoSortMethod topoSortMethod=new TopoSortMethod();int[] sortedArray =topoSortMethod.sort(graph);}}


输出结果:

0--->4--->2--->3--->5--->1--->



0 0
原创粉丝点击