LintCode 127. Topological Sorting
给定一个有向图,图节点的拓扑排序定义如下:
对于图中的每一条有向边 A -> B , 在拓扑排序中A一定在B之前.
拓扑排序中的第一个节点可以是图中的任何一个没有其他节点指向它的节点.
针对给定的有向图找到任意一种拓扑排序的顺序.
思路:
首先要找到starting node,也就是in-degree = 0的node。在直接找起点之前,把given的每个node都traverse一遍,并且用一个hashmap记录他们“被neighbor”的次数,也就是他们的in-degree。(第一个循环)
接下来,用另外一个循环, 在map中查找每一个node。如果这个node没有在map中出现过,那么意味着这个node的入度为0,也就是我们需要找的starting node。把这些starting node加入到好基友中(queue q 和arraylsit result)。
最后,BFS搜索,找出一条topologicla sorting的路线。注意:如果一个图有多个starting node,那么[starting node1, starting node2, starting node3, … ]这种排序也是可以的。
/**
* Definition for Directed graph.
* class DirectedGraphNode {
* int label;
* ArrayList<DirectedGraphNode> neighbors;
* DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
* };
*/
public class Solution {
/*
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
// write your code here
ArrayList<DirectedGraphNode> result = new ArrayList <>();
HashMap<DirectedGraphNode, Integer> map = new HashMap<>();
//Find all in-degrees
for(DirectedGraphNode node : graph){
for(DirectedGraphNode neighbor : node.neighbors){
if(map.containsKey(neighbor)){
map.put(neighbor, map.get(neighbor)+1);
}else{
map.put(neighbor, 1);
}
}
}
//Find all starting nodes
Queue <DirectedGraphNode> q = new LinkedList<DirectedGraphNode>();
for(DirectedGraphNode node : graph){
if(!map.containsKey(node)){
q.offer(node);
result.add(node); //Start populating the result list
}
}
//BFS
while(!q.isEmpty()){
DirectedGraphNode node = q.poll();
for(DirectedGraphNode n : node.neighbors){
map.put(n, map.get(n) - 1);
if(map.get(n) == 0){
result.add(n);
q.offer(n);
}
}
}
return result;
}
}