要看数据结构的话,给一个大佬的博客,很详细
http://www.cnblogs.com/skywang12345/p/3603935.html
正题
我们现在来侃一下拓扑排序,简而言之,就是从有向无环图中找出要给有序的线性序列
把没有结点指向的结点先拿出来,根据先后排序,再把它从邻接矩阵中删除,递归调用
就这样,一直进行下去,就会得到最终结果。
给出我的代码
1 package com.java.demo.算法.图.拓扑排序.test; 2 3 4 import org.junit.Test; 5 6 import java.util.ArrayList; 7 import java.util.List; 8 9 public class Graph { 10 private char[] points; 11 private int edges[][]; 12 private int num; //结点的个数 13 14 public Graph() { 15 } 16 17 public Graph(char[] points, char[][] edges) { 18 this.points = points; 19 this.num = points.length; 20 this.edges = new int[num][num]; 21 for (char[] edge : edges) { 22 this.edges[getPosition(edge[0])][getPosition(edge[1])] = 1; 23 } 24 } 25 26 //打印邻接矩阵信息 27 public void print(){ 28 System.out.print(" "); 29 for (char point : points) { 30 System.out.print(point+" "); 31 } 32 System.out.println(); 33 for (int i=0;i<num;i++){ 34 System.out.print(points[i]+" "); 35 for (int j=0;j<num;j++){ 36 System.out.print(edges[i][j]+" "); 37 } 38 System.out.println(); 39 } 40 } 41 42 public int getPosition(char ch){ 43 for (int i=0;i<num;i++){ 44 if (ch == points[i]){ 45 return i; 46 } 47 } 48 return -1; 49 } 50 51 52 public void doFilter(int edges[][],char points[],List<Character> rets){ 53 int num = points.length; //存放结点的数量 54 List<Integer> list = new ArrayList<>(); 55 for (int j=0;j<num;j++){ 56 for (int i=0;i<num;i++){ 57 if (edges[i][j] == 1){ 58 list.add(j); 59 break; 60 } 61 } 62 } 63 for (int i=0;i<num;i++){ 64 if (!list.contains(i)){ 65 rets.add(points[i]); 66 } 67 } 68 num = list.size(); 69 if (num == 0){ 70 return; 71 } 72 int newEdges[][] = new int[num][num]; 73 char newPoints[] = new char[num]; 74 for (int i=0;i<num;i++){ 75 newPoints[i] = points[list.get(i)]; 76 } 77 for (int i=0;i<num;i++){ 78 for (int j=0;j<num;j++){ 79 newEdges[i][j] = edges[list.get(i)][list.get(j)]; 80 } 81 } 82 doFilter(newEdges,newPoints,rets); 83 } 84 85 86 //拓扑排序 87 public void topSort(){ 88 List<Character> rets = new ArrayList<>(); 89 doFilter(edges,points,rets); 90 91 for (Character ret : rets) { 92 System.out.print(ret+" "); 93 } 94 95 // for (int i=0;i<num;i++){ 96 // for (int j=0;j<num;j++){ 97 // if (edges[j][i] == 1){ 98 // queue.add(points[i]); 99 // break; 100 // } 101 // } 102 // } 103 // 104 // for (Character character : queue) { 105 // System.out.println(); 106 // System.out.print(character+" "); 107 // } 108 } 109 110 public static void main(String[] args) { 111 char points[] = {'A','B','C','D','E'}; 112 char edges[][] = { 113 {'A','B'}, 114 {'B','D'}, 115 {'C','D'}, 116 {'D','E'}, 117 }; 118 Graph t = new Graph(points, edges); 119 120 // t.print(); 121 //// 122 t.topSort(); 123 } 124 }