Topological Sorting
来源:互联网 发布:yum clean all 编辑:程序博客网 时间:2024/05/29 15:48
Given an directed graph, a topological order of the graph nodes is defined as follow:
For each directed edge A -> B in 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.
Have you met this question in a real interview? Yes
Example
For graph as follow:
picture
The topological order can be:
[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
…
/** * 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 ArrayList<DirectedGraphNode> result = new ArrayList<DirectedGraphNode>(); HashMap<DirectedGraphNode, Integer> map = new HashMap();//hash 表 for (DirectedGraphNode node : graph) { for (DirectedGraphNode neighbor : node.neighbors) { if (map.containsKey(neighbor)) { map.put(neighbor, map.get(neighbor) + 1); } else { map.put(neighbor, 1); } } } Queue<DirectedGraphNode> q = new LinkedList<DirectedGraphNode>(); for (DirectedGraphNode node : graph) { if (!map.containsKey(node)) { q.offer(node); result.add(node); } } while (!q.isEmpty()) { //队列 DirectedGraphNode node = q.poll(); for (DirectedGraphNode n : node.neighbors) { map.put(n, map.get(n) - 1); if (map.get(n) == 0) {//入度为零时 弹出 result.add(n); q.offer(n); } } } return result; }}
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
- 关于sqlite外键
- 阿里云windows服务器下的我的世界配置失败内存超限的问题
- Read only file system on Android
- 利用统一资源标识符管理应用状态信息
- 【Hibernate】Hibernate 利用缓存(一级、二级、查询)提高系统性能
- Topological Sorting
- Hotspot JVM的常用选项
- Struts2--思维导图
- select真的有限制吗
- 修改gradle库下载地址
- leetcode之Odd Even Linked List
- vctor容器的使用
- linux mysql安装
- linux ntp 安装配置