127.Topological Sorting
Last updated
Last updated
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...class DirectedGraphNode {
int label;
ArrayList<DirectedGraphNode> neighbors;
DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
};
public class Solution_127 {
/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
//Indegree
HashMap<DirectedGraphNode,Integer> map=new HashMap<>();
for(DirectedGraphNode node: graph){
for(DirectedGraphNode element: node.neighbors){
if(map.containsKey(element)){
map.put(element,map.get(element)+1);
}
else{
map.put(element,1);
}
}
}
//队列放入度为0的点,但是入度为0的点可能不止一个,入度为0的点不存在map中
Queue<DirectedGraphNode> queue=new LinkedList<DirectedGraphNode>();
ArrayList<DirectedGraphNode> result=new ArrayList<DirectedGraphNode>();
for(DirectedGraphNode node: graph){
if(!map.containsKey(node)){
queue.offer(node);
result.add(node);
}
}
while(!queue.isEmpty()){
DirectedGraphNode current=queue.poll();
for(DirectedGraphNode node:current.neighbors){
map.put(node,map.get(node)-1);
if(map.get(node)==0){
queue.offer(node);
result.add(node);
}
}
}
return result;
}