算法之4--拓扑排序

    转眼已经是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--->



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值