您的位置:首页 > 其它

算法之4--拓扑排序

2015-11-29 21:12 351 查看
转眼已经是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--->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: