# Topological Sorting

93人阅读 评论(0)

/**
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
ArrayList<DirectedGraphNode> results = new ArrayList<>();
if (graph == null) {
return results;
}
Map<DirectedGraphNode, Integer> map = new HashMap<>();
for (DirectedGraphNode node: graph) {
for (DirectedGraphNode neighborNode: node.neighbors) {
if (map.containsKey(neighborNode)) {
map.put(neighborNode, map.get(neighborNode) + 1);
} else {
map.put(neighborNode, 1);
}
}
}

for (DirectedGraphNode node: graph) {
if (!map.containsKey(node)) {
queue.offer(node);
}
}

while (!queue.isEmpty()) {
DirectedGraphNode node = queue.poll();
for (DirectedGraphNode neighborNode: node.neighbors) {
map.put(neighborNode, map.get(neighborNode) - 1);
if (map.get(neighborNode) == 0) {
queue.offer(neighborNode);
}
// int num = map.get(neighborNode);
// if (num != 0) {
//     map.put(neighborNode, num - 1);
// } else {
//     queue.offer(neighborNode);
// }
}
}
return results;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：72148次
• 积分：8180
• 等级：
• 排名：第2544名
• 原创：795篇
• 转载：2篇
• 译文：0篇
• 评论：0条
文章分类
阅读排行