算法之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--->
相关文章推荐
- Java自定义注解及注解的使用
- Manifest与TypeTag
- IOS工作小结
- Http长连接
- 存储过程的简化--只记录了问题--项目结束后一并优化
- MySQL递归查询树状表的子节点、父节点
- 关于lua语言及热更新的研究一
- Div+CSS总结
- mysql之存储引擎
- TCP协议疑难杂症全景解析
- 备忘录--关于硬盘挂载的问题
- 一起talk C栗子吧(第六十八回:C语言实例--DIY字符串长度函数的小疑问)
- 华为oj 公共字串计算
- Hive安装(一)之环境配置
- hpuoj 1715: 感恩节KK专场——2015年的第一场雪 【分类转化思想】【校赛】
- LeetCode(1)--Two Sum
- mysql之Unknown storage engine 'InnoDB'
- HTML基础知识
- 命名不规范引发的DropDownListFor无法选中
- VS2012 error C2664: “std::make_pair”:无法将左值绑定到右值引用