/**
* 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) {
// an arraylist to save the result
ArrayList<DirectedGraphNode> ret = new ArrayList<>();
// calculate indegree for the nodes in the graph
// using a hashmap to save the <node, indegree> pair
HashMap<DirectedGraphNode, Integer> map = new HashMap<>();
for (DirectedGraphNode node : graph) {
// list all neighbors of the node
for (DirectedGraphNode neighbor : node.neighbors) {
if (map.containsKey(neighbor)) {
map.put(neighbor, map.get(neighbor)+1);
}
else {
map.put(neighbor, 1);
}
}
}
// find the root(s) in graph, note that root does not exist in the map
// put all root(s) into the queue
Queue<DirectedGraphNode> queue = new LinkedList<>();
for (DirectedGraphNode node : graph) {
if (!map.containsKey(node)) {
queue.offer(node);
ret.add(node);
}
}
// do the BFS in the graph
while (!queue.isEmpty()) {
// we don't need a for loop to iterate all nodes in the queue b/c we just need to return one
// topological order for the given graph
DirectedGraphNode node = queue.poll();
for (DirectedGraphNode neighbor : node.neighbors) {
// decrease all indegree of node's neighbors by 1 b/c we just add node to our result
map.put(neighbor, map.get(neighbor)-1);
// if a node's indegree is 0, we need to put it into the queue
if (map.get(neighbor) == 0) {
queue.offer(neighbor);
ret.add(neighbor);
}
}
}
return ret;
}
}
Topological Sorting
最新推荐文章于 2022-06-01 13:11:23 发布