算法思路:
拓扑排序:
* 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 stub
List<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 sort
char[] 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