拓扑排序
来源:互联网 发布:掌上电力提示网络问题 编辑:程序博客网 时间:2024/06/12 18:30
算法思路:
拓扑排序:
* 1.找到一个没有后继的顶点
* 2.从图中删除这个顶点,在列表的前面插入顶点的标记
代码如下:
import java.util.Arrays;import java.util.LinkedList;import java.util.List;/* * 拓扑排序: * 1.找到一个没有后继的顶点 * 2.从图中删除这个顶点,在列表的前面插入顶点的标记 */public class TopoSort {public static void main(String[] args) {// TODO Auto-generated method stubList<Character> vertices = new LinkedList<Character>(Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'));List<LinkedList<Integer>> adjMatrix = new LinkedList<LinkedList<Integer>>();adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 1, 1, 0, 0, 0)));adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 1, 0, 0, 0)));adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 1, 0, 0, 0)));adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 1, 0)));adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 1, 0)));adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 0, 1)));adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 0, 1)));adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0)));//topo sortchar[] sortedArr = new char[vertices.size()];while(vertices.size() > 0) {int curVertex = noSuccessors(adjMatrix);if(curVertex == -1) {System.out.println("Graph has cycles");} else {sortedArr[vertices.size()-1] = vertices.get(curVertex);//delete....vertices.remove(curVertex);adjMatrix.remove(curVertex);for(List<Integer> r : adjMatrix) { r.remove(curVertex);}}}for(char ch : sortedArr) {System.out.print(ch + " ");}System.out.println();}public static int noSuccessors(List<LinkedList<Integer>> adjMatrix) {int curRow = 0;boolean isEdge = false;for(List<Integer> r : adjMatrix) {isEdge = false;for(int c : r) {if(c == 1) {isEdge = true;break;}}if(!isEdge) {return curRow; }curRow++;}return -1;}}
输出结果是:
C B A E D G F H
0 0
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 【拓扑排序】
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 拓扑排序
- 高性能IO设计的Reactor和Proactor模式
- 用js操作属性的两种方法
- View Programming Guide for IOS:Views笔记
- mac 安装和运行go的helloword
- 新装修的房子甲醛主要是来自哪些材料?
- 拓扑排序
- JavaScript中文本光标定位
- UIView常用的一些方法小记之setNeedsDisplay和setNeedsLayout
- 1的个数
- void(*p)()和void*p()区别
- WPF单实例限制
- 开源一个C++实现的简单HTTP协议处理库
- 背包九讲
- easyui datagrid 多表头设置