- For each directed edge
A -> B
in graph, A must before B in the order list. - The first node in the order can be any node in the graph with no nodes direct to it.
BFS (??)
使用queue
/**
* 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
if (graph == null || graph.size() == 0) {
return graph;
}
ArrayList<DirectedGraphNode> rst = new ArrayList<>();
// keep track of all neighbors in HashMap
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
// 找到所有被directed的点并记录被directed多少次
for (DirectedGraphNode node : graph) {
for (DirectedGraphNode neighbor : node.neighbors) {
int key = neighbor.label;
if (map.containsKey(key)) {
map.put(key, map.get(key) + 1);
} else {
map.put(key, 1);
}
}
}
// find all the root which never be directed and cannot be found in map
Queue<DirectedGraphNode> queue = new LinkedList<> ();
for (DirectedGraphNode node : graph) {
if (!map.containsKey(node.label)) {
queue.offer(node);
rst.add(node);
}
}
// BFS: according the node in queue to proccess
while (!queue.isEmpty()) {
DirectedGraphNode node = queue.poll();
for (DirectedGraphNode neighbor : node.neighbors) {
int key = neighbor.label;
map.put(key, map.get(key)-1);
if(map.get(key) == 0) {
queue.offer(neighbor);
rst.add(neighbor);
}
}
}
return rst;
}
}
No comments:
Post a Comment