Topological Sorting
Given an directed graph, a topological order of the graph nodes is defined as follow:
- For each directed edge
A -> Bin 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.
Find any topological order for the given graph.
Notice
You can assume that there is at least one topological order in the graph.
Clarification
Learn more about representation of graphs
Example
For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
Solution 1: indegree and BFS.
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
ArrayList<DirectedGraphNode> res = new ArrayList<DirectedGraphNode>();
if(graph == null || graph.size() == 0) {
return res;
}
Map<DirectedGraphNode, Integer> indegree = new HashMap<DirectedGraphNode, Integer>();
computeIndegree(graph, indegree);
bfs(graph, res, indegree);
return res;
}
public void computeIndegree(ArrayList<DirectedGraphNode> graph, Map<DirectedGraphNode, Integer> indegrees) {
for(DirectedGraphNode node : graph) {
for(DirectedGraphNode n : node.neighbors) {
if(indegrees.containsKey(n)) {
indegrees.put(n, indegrees.get(n) + 1);
}
else {
indegrees.put(n, 1);
}
}
}
}
public void bfs(ArrayList<DirectedGraphNode> graph, ArrayList<DirectedGraphNode> res, Map<DirectedGraphNode, Integer> indegree) {
Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();
for(DirectedGraphNode n : graph) {
if(!indegree.containsKey(n)) {
queue.offer(n);
}
}
while(!queue.isEmpty()) {
DirectedGraphNode tmp = queue.poll();
res.add(tmp);
for(DirectedGraphNode nn : tmp.neighbors) {
int degree = indegree.get(nn) - 1;
indegree.put(nn, degree);
if(degree == 0) {
queue.offer(nn);
}
}
}
}
Solution 2: DFS, recursion. No matter which point start, it will go to deepest node first. Bottom up.
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
ArrayList<DirectedGraphNode> res = new ArrayList<DirectedGraphNode>();
if(graph == null || graph.size() == 0) {
return res;
}
HashSet<DirectedGraphNode> isVisited = new HashSet<DirectedGraphNode>();
for(DirectedGraphNode n : graph) {
if(!isVisited.contains(n)) {
dfs(n, res, isVisited);
}
}
return res;
}
public void dfs(DirectedGraphNode node, ArrayList<DirectedGraphNode> res, HashSet<DirectedGraphNode> isVisited) {
if(node == null) {
return ;
}
isVisited.add(node);
for(DirectedGraphNode n : node.neighbors) {
if(!isVisited.contains(n)) {
dfs(n, res, isVisited);
}
}
res.add(0, node);
}