有向图,无环, 有入度为零 的 点
- 先看哪个点是入度为0的点 比如A
- 然后把 以 A出发的 路径叉掉
- 找下一个入度为0的点 。 重复操作
public static void sortedTopology(Graph graph) {
// 拓扑排序
// 保存 节点剩余的入度
HashMap<Node, Integer> inMap = new HashMap<>();
// 保存 入度为0 的节点 的队列
LinkedList<Node> zeroInQueue = new LinkedList<>();
for (Node node : graph.nodes.values()) {
inMap.put(node, node.in);
if (node.in == 0) {
zeroInQueue.add(node);
}
}
// 保存排序结果
List<Node> result = new ArrayList<>();
while(!zeroInQueue.isEmpty()){
Node cur = zeroInQueue.poll();
result.add(cur);
for(Node next : cur.nexts){
// 修改 以当前节点 出发的路径 的 节点 的入度
inMap.put(next, inMap.get(next) - 1);
// 如果当前节点的入度为0,也加入 zeroInQueue
if(inMap.get(next) == 0){
zeroInQueue.add(next);
}
}
}
}