LintCode Topological Sorting
2015-10-12 22:58
323 查看
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]
...
Note
You can assume that there is at least one topological order in the graph.
Challenge
Can you do it in both BFS and DFS?
首先给出一个DFS的,这个以前倒是没这么写
/** * Definition for Directed graph. * struct DirectedGraphNode { * int label; * vector<DirectedGraphNode *> neighbors; * DirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { private: unordered_set<DirectedGraphNode*> visited; 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 visited.clear(); vector<DirectedGraphNode*> path; for (auto node : graph) { dfs(node, path); } reverse(path.begin(), path.end()); return path; } void dfs(DirectedGraphNode* node, vector<DirectedGraphNode*>& path) { if (visited.count(node) > 0) { return; } visited.insert(node); for (auto n : node->neighbors) { dfs(n, path); } path.push_back(node); } };
相关文章推荐
- Linux鸟哥私房菜学习笔记(三)
- linux VM中复制虚拟机后eth0变成eth1
- Linux上安装Nginx及常用命令
- 文件的copy(一次性完成数据的传递 )
- AbstractFactory(PeopleSkin)
- 精品软件推荐 Desktop Central - Free Windows Admin Tools
- 精品软件推荐 Desktop Central - Free Windows Admin Tools
- CentOS 7.0,启用iptables防火墙
- Tomcat报错:Address already in use: JVM_Bind 端口被占用
- Linux学习笔记(3)
- hdu5072Coprime
- linux shell 编程1文件权限检测、字符串比较判断、数值大小比较、时间获取以及单引号双引号反引号等的使用
- [BZOJ1646] [Usaco2007 Open]Catch That Cow 抓住那只牛
- Shell基础-环境变量配置文件
- Linux下XAMPP的部署实战
- Linux监控软件之 Cacti
- windows下 简单配置PHP + apache +mysql
- linux的OPEN系统调用
- 游戏系统开发笔记(六)——服务端架构设计
- 用标签查看linux内核