Topological Sorting
public class Solution {
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
HashMap<DirectedGraphNode, Integer> map = new HashMap();
for (DirectedGraphNode node : graph) {
if(!map.containsKey(node)) map.put(node, 0);
for (DirectedGraphNode neighbor : node.neighbors) {
if (map.containsKey(neighbor)) {
map.put(neighbor, map.get(neighbor) + 1);
} else {
map.put(neighbor, 1);
}
}
}
ArrayList<DirectedGraphNode> result = new ArrayList<DirectedGraphNode>();
for(DirectedGraphNode node : graph){
if(!map.containsKey(node) || map.get(node) == 0)dfs(node, map, graph, result);
}
return result;
}
public void dfs(DirectedGraphNode node,
HashMap<DirectedGraphNode, Integer> map,
ArrayList<DirectedGraphNode> graph,
ArrayList<DirectedGraphNode> result){
map.put(node, -1);
result.add(node);
for(DirectedGraphNode neighbor : node.neighbors){
map.put(neighbor, map.get(neighbor) - 1);
if(map.get(neighbor) == 0) dfs(neighbor, map, graph, result);
}
return ;
}
}
class Solution:
"""
@param: graph: A list of Directed graph node
@return: Any topological order for the given graph.
"""
def topSort(self, graph):
#define indegree with dict
indegree = dict((i,0) for i in graph)
for i in graph:
for j in i.neighbors:
indegree[j]+=1
#define queue and put the 0 degree nodes
import Queue
q = Queue.Queue()
for i in graph:
if indegree[i] == 0:
q.put(i)
#result and bfs
result = []
while not q.empty():
node = q.get()
result.append(node)
for j in node.neighbors:
indegree[j]-=1
if indegree[j] == 0:
q.put(j)
return result
最后更新于
这有帮助吗?