packagegraphics.dag.topologicalsort;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;/*** 有向无环图所有的走法
*@authorzhangxinren
**/
public classTopologicalSort {//所有的走法
private static List> result = new ArrayList<>();//顶点和边的邻接表
private static int[][] edges = {//14个顶点,索引0不用,邻接表
{},
{3},
{4},
{4,5},
{6},
{6},
{7,11},
{8},
{13},
{10},
{11},
{12},
{13},
{14},
{}
};//每条边的入度
private static int[] inDegree;//邻接表元素个变化,inDegree初始长度也变化//当前可以走的边(入度为0的边)
private static List next = new ArrayList<>();;
// 思路:利用递归,每次递归用掉一个入度为0的顶点,将用掉的顶点加入临时结果中,当没有入度为0的顶点时,将临时结果加入结果集中,
// 每用掉一个入度为0的顶点,更新顶点的入度数组和入度为0的顶点的数组public static void topologicalSort(List oneResult, int[] inDegree, Listnext){if(next.size() > 0){for(int i = 0; i < next.size(); i++){
List tempNext = new ArrayList<>(next);
List tempOneResult = new ArrayList<>(oneResult);
tempNext.remove(next.get(i));
tempOneResult.add(next.get(i));int[] tempInDegree =Arrays.copyOf(inDegree, inDegree.length);int[] tempEdges =edges[next.get(i)];for(int j = 0; j < tempEdges.length; j++){
tempInDegree[tempEdges[j]]--;if(tempInDegree[tempEdges[j]] == 0){
tempNext.add(tempEdges[j]);
}
}
topologicalSort(tempOneResult, tempInDegree, tempNext);
}
}else{
result.add(oneResult);
}
}public static voidmain(String[] args) {//索引0不用
inDegree = new int[15];for(int i = 0; i < inDegree.length; i++){
inDegree[i]= 0;
}for(int i = 1; i < edges.length; i++){for(int j = 0; j < edges[i].length; j++){
inDegree[edges[i][j]]++;
}
}for(int i = 1; i < inDegree.length; i++){if(inDegree[i] == 0){
next.add(i);
}
}
topologicalSort(new ArrayList<>(), inDegree, next);for(int i = 0; i < result.size(); i++){for(int j = 0; j < result.get(i).size(); j++){
System.out.print(result.get(i).get(j)+ " ");
}
System.out.println();
}
}
}