Lintcode - Topological Sorting
来源:互联网 发布:苏州方正软件 编辑:程序博客网 时间:2024/06/10 17:21
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; }
0 0
- Lintcode - Topological Sorting
- lintcode:Topological Sorting
- lintcode:Topological Sorting
- LintCode Topological Sorting
- 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
- ural 1280. Topological Sorting
- [刷题]Topological Sorting
- Gas Station
- 【Boost】Boost总结汇总
- EBS_R12_Web_ADI_使用手册
- java class loader 学习
- 图论——最短路径——floyd
- Lintcode - Topological Sorting
- iOS学习-初学者如何使用块(Block)进行传值
- Android学习(20)-百度地图使用
- GCC 命令行详解
- Java笔记十八.内部类和匿名类
- iphone开发之深入浅出(1) - ARC是什么
- iOS archive(归档)的总结
- CODEVS 1430 素数判定
- 【iOS知识学习】_视图控制对象生命周期-init、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear等的区别及用途