#127 Topological Sorting
来源:互联网 发布:机顶盒看直播软件 编辑:程序博客网 时间:2024/06/05 12:37
题目描述:
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.
Notice
You can assume that there is at least one topological order in the graph.
Clarification
Learn more about representation of graphs
Example
题目思路:For graph as follow:
The topological order can be:
[0, 1, 2, 3, 4, 5][0, 2, 3, 1, 5, 4]...
topological sort应该是经典算法之一吧,随便google两下就可以找到一堆解法。我是参考了下面的链接写的code:
DAG算法
Mycode(AC = 201ms):
/** * Definition for Directed graph. * struct DirectedGraphNode { * int label; * vector<DirectedGraphNode *> neighbors; * DirectedGraphNode(int x) : label(x) {}; * }; */class Solution {public: /** * @param graph: A list of Directed graph node * @return: Any topological order for the given graph. */ vector<DirectedGraphNode*> topSort(vector<DirectedGraphNode*> graph) { // write your code here vector<DirectedGraphNode*> ans; unordered_set<int> visited; for (int i = 0; i < graph.size(); i++) { if (visited.find(graph[i]->label) == visited.end()) { // for each unvisited node, find its reversed // topsort dfs(ans, visited, graph, graph[i]); } } reverse(ans.begin(), ans.end()); return ans; } void dfs(vector<DirectedGraphNode*>& ans, unordered_set<int>& visited, vector<DirectedGraphNode*>& graph, DirectedGraphNode* node) { if (visited.find(node->label) != visited.end()) { return; } // use dfs to go finding the bottom unvisited node for (int i = 0; i < node->neighbors.size(); i++) { dfs(ans, visited, graph, node->neighbors[i]); } // once all the neighbors are found, then insert the current // node visited.insert(node->label); ans.push_back(node);// 4, 1 }};
0 0
- #127 Topological Sorting
- #127 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
- Lintcode - Topological Sorting
- ural 1280. Topological Sorting
- [刷题]Topological Sorting
- URAL 1280 Topological Sorting
- 1035: 相同生日
- 最短路径--->Dijkstra算法
- 巧用可变参数宏、编译器内置宏和printf输出调试信息
- POJ 1384 Piggy-Bank (01背包)
- windows和linux中检查端口是否被占用
- #127 Topological Sorting
- 301、404、200、304等HTTP状态
- POJ-3320 Jessica's Reading Problem 【尺取(or 二分)+STL】
- 前端程序员必须知道的高性能Javascript知识
- YII url美化管理
- DirectX3D游戏制作之---3D场景的渲染及人物动画的显示
- C#生成树结构列表函数
- Java中的private、protected、public和default的区别
- Spring集成Quartz定时任务