Thoughts:
1. For each node in the graph, construct a map with node as key, and number of parent nodes as value
2. Looping through left nodes and see if its indegree is 0: if so, remove the node from graph and add it to result; also its neighbors indegree--
A problem while implementing #2 is ConcurrentModificatoinException that I tried to remove the node from map while looping through it. A work around is looping through remaining nodes from graph and remove it from graph directly. Entries in map are never removed.
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
ArrayList<DirectedGraphNode> result = new ArrayList<DirectedGraphNode>();
if (graph == null) {
return result;
}
Map<DirectedGraphNode, Integer> map = new HashMap<DirectedGraphNode, Integer>();
for (DirectedGraphNode node : graph) {
map.put(node, 0);
}
for (DirectedGraphNode node : graph) {
for (DirectedGraphNode neighbor : node.neighbors) {
map.put(neighbor, map.get(neighbor)+1);
}
}
while (!graph.isEmpty()) {
int index = 0;
while (index < graph.size()) {
DirectedGraphNode node = graph.get(index);
if (map.get(node).equals(0)) {
result.add(node);
graph.remove(node);
for (DirectedGraphNode neighbor : node.neighbors) {
map.put(neighbor, map.get(neighbor)-1);
}
} else {
index++;
}
}
}
return result;
}