什么是拓扑排序?
在一个工程项目中,所做的事情肯定是有先后的,比如盖楼的时候得先打地基,然后砌砖,最后才可以刷墙。
那么顺序就是打地基---》砌砖---》刷墙
我们把这三个步骤,按照上述顺序给排一下序,就是所谓的拓扑排序。
那么在图中就是没有箭头指向的节点是最先开始的。也就是入度为0的点。当进行完一个入度为0的点时,我们把它的影响消掉,就是它箭头指向的节点的入度要减1。然后再从剩余的节点中寻找是否有入度为0的点,如果有的继续循环。
public static List<Node> sortedTopology(Graph graph){
//key表示节点,value表示剩余的入度
HashMap<Node,Integer> map = new HashMap<Node, Integer>();
Queue<Node> zeroInQueue = new LinkedList<Node>();
for(Node next:graph.nodes.values()) {
if(next.in==0) {
zeroInQueue.add(next);
}
map.put(next, next.in);
}
List<Node> result = new ArrayList<Node>();
while(!zeroInQueue.isEmpty()) {
Node cur = zeroInQueue.poll();
result.add(cur);
for(Node next:cur.nexts) {
//消除cur节点带来的入度影响。
map.put(next, map.get(next)-1);
//put可以是加入也可以是更新操作。
if(map.get(next)==0) {
zeroInQueue.add(next);
}
}
}
return result;
}