Topology Sort
Topology Sort
/**
* 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) {
Map<DirectedGraphNode, Integer> map = new HashMap<>();
// Count the flow in number of each node
for (DirectedGraphNode node: graph){
for (DirectedGraphNode neighbor: node.neighbors){
map.put(neighbor, map.getOrDefault(neighbor, 0) + 1);
}
}
ArrayList<DirectedGraphNode> ans = new ArrayList<>();
Queue<DirectedGraphNode> queue = new LinkedList<>();
// Find the heads of graph
for (DirectedGraphNode node: graph){
if (!map.containsKey(node)){
queue.add(node);
ans.add(node);
}
}
// start to put node to ans
while(!queue.isEmpty()){
DirectedGraphNode curNode = queue.poll();
for (DirectedGraphNode node: curNode.neighbors){
map.put(node , map.get(node) - 1);
if (map.get(node) == 0){
queue.add(node);
ans.add(node);
}
}
}
return ans;
}
}210 Course Schedule
269 Alien Dictionary
Last updated