Topological Sorting
来源:互联网 发布:c语言whilet--的用法 编辑:程序博客网 时间:2024/05/29 15:44
拓扑排序非常重要的一种考题。
topological sort的重点在于如何找到排序的入口
java
/** * 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) { return null; } Map<DirectedGraphNode, Integer> map = new HashMap<>(); for (DirectedGraphNode node : graph) { for (DirectedGraphNode val : node.neighbors) { if (map.containsKey(val)) { map.put(val, map.get(val) + 1); } else { map.put(val, 1); } } } Queue<DirectedGraphNode> queue = new LinkedList<>(); ArrayList<DirectedGraphNode> list = new ArrayList<>(); for (DirectedGraphNode node : graph) { if (!map.containsKey(node)) { queue.offer(node); list.add(node); } } while (!queue.isEmpty()) { DirectedGraphNode node = queue.poll(); for (DirectedGraphNode val : node.neighbors) { map.put(val, map.get(val) - 1); if (map.get(val) == 0) { queue.offer(val); list.add(val); } } } return list; }}
python
"""Definition for a Directed graph nodeclass DirectedGraphNode: def __init__(self, x): self.label = x self.neighbors = []"""import Queueclass Solution: """ @param: graph: A list of Directed graph node @return: Any topological order for the given graph. """ def topSort(self, graph): # write your code here if graph is None: return None mapping, arr, queue = {}, [], Queue.Queue() for ele in graph: for val in ele.neighbors: if val in mapping: mapping[val] = mapping[val] + 1 else: mapping[val] = 1 for ele in graph: if ele not in mapping: arr.append(ele) queue.put(ele) while not queue.empty(): node = queue.get() for ele in node.neighbors: mapping[ele] = mapping[ele] - 1 if mapping[ele] == 0: queue.put(ele) arr.append(ele) return arr
阅读全文
0 0
- Topological sorting
- Topological sorting
- Topological Sorting
- Topological Sorting
- Topological Sorting
- Topological Sorting
- Topological Sorting
- Ural 1280. Topological Sorting
- ural 1280. Topological Sorting
- ural 1280Topological Sorting
- timus 1280 Topological Sorting
- [Random Coding]Topological Sorting
- Lintcode - Topological Sorting
- ural 1280. Topological Sorting
- [刷题]Topological Sorting
- URAL 1280 Topological Sorting
- lintcode:Topological Sorting
- lintcode:Topological Sorting
- c++中为什么不提倡使用vector<bool>(转)
- class中自身调用方法
- python面向对象
- C++猜数字游戏
- Bear and Blocks CF-574D(类似dp+思维)
- Topological Sorting
- js的类型检测
- C/C++ 撸一段流行的观察者模式
- FL2440
- 树上方法总结 LCA 树上倍增 树链剖分 树的直径 重心
- 表单验证
- nexus配置以及部署在tomcat中
- 各种语言注释标注总结
- nginx源码阅读(十).ngx_event_core_module模块