Lintcode: Topological Sorting
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.
Note
You can assume that there is at least one topological order in the graph. Example
For graph as follow:
The topological order can be: [0, 1, 2, 3, 4, 5] or [0, 2, 3, 1, 5, 4] or .... Challenge
Can you do it in both BFS and DFS?
这道题参考了网上一些很好的思路:
method1: Record the pre nodes of every node, then find out a node without pre node in each iteration and delete this node from unvisited set, add this node to result.
/**
* 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> res = new ArrayList<DirectedGraphNode>();
if (graph.size() == 0) return res;
HashMap<DirectedGraphNode, Set<DirectedGraphNode>> map = new HashMap<DirectedGraphNode, Set<DirectedGraphNode>>();
for (DirectedGraphNode each : graph) {
map.put(each, new HashSet<DirectedGraphNode>());
}
for (DirectedGraphNode each : graph) {
for (int i=0; i<each.neighbors.size(); i++) {
map.get(each.neighbors.get(i)).add(each);
}
}
while (graph.size() > 0) {
int index = 0;
while (index < graph.size()) {
DirectedGraphNode cur = graph.get(index);
if (map.get(cur).size() == 0) {
//add the node to our result
//remove the node from the graph
res.add(cur);
graph.remove(index);
for (DirectedGraphNode elem : graph) {
if (map.get(elem).contains(cur)) {
map.get(elem).remove(cur);
}
}
}
else index++;
}
}
return res;
}
}
method2: DFS: use a recursive method, randomly pick up an unmakred node, before adding it into result list, recursively visite all its neighbors and add its neighbors into list first. In this way, we guarantee that all the nodes belong to some node's post nodes will be added to the result list first.
To be more specific, we can modify DFSto find Topological Sorting of a graph. In DFS, we start from a vertex, we first print it and then recursively call DFS for its adjacent vertices. In topological sorting, we don’t print the vertex immediately, we first recursively call topological sorting for all its adjacent vertices, then print the current vertex. In this way, we ensure a node's neighbor nodes are always added before the node itself.
/**
* 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> res= new ArrayList<DirectedGraphNode>();
if (graph.size() == 0) return res;
HashMap<DirectedGraphNode, Integer> status = new HashMap<DirectedGraphNode, Integer>();
for (DirectedGraphNode elem : graph) {
status.put(elem, 0);
}
ArrayList<DirectedGraphNode> templist = new ArrayList<DirectedGraphNode>();
templist.add(null);
while (hasUnvisited(graph, status, templist)) {
DirectedGraphNode cur = templist.get(0);
templist.set(0, null);
search(cur, status, res);
}
return res;
} public boolean hasUnvisited(ArrayList<DirectedGraphNode> graph, HashMap<DirectedGraphNode, Integer> status, ArrayList<DirectedGraphNode> templist) {
for (DirectedGraphNode elem : graph) {
if (status.get(elem) == 0) {
templist.set(0, elem);
return true;
}
}
return false;
} public void search(DirectedGraphNode cur, HashMap<DirectedGraphNode, Integer> status, ArrayList<DirectedGraphNode> res) {
if (status.get(cur) == 1) System.out.println("not a DAG");
if (status.get(cur) == 2) return;
status.put(cur, 1);
for (DirectedGraphNode neigh : cur.neighbors) {
search(neigh, status, res);
}
status.put(cur, 2);
res.add(0, cur);
}
}
Lintcode: Topological Sorting的更多相关文章
- hdu.5195.DZY Loves Topological Sorting(topo排序 && 贪心)
DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 ...
- URAL(timus) 1280 Topological Sorting(模拟)
Topological Sorting Time limit: 1.0 secondMemory limit: 64 MB Michael wants to win the world champio ...
- Topological Sorting
Topological sorting/ ordering is a linear ordering of its vertices such that for every directed edge ...
- Union - Find 、 Adjacency list 、 Topological sorting Template
Find Function Optimization: After Path compression: int find(int x){ return root[x] == x ? x : (root ...
- 拓扑排序(Topological Sorting)
一.什么是拓扑排序 在图论中,拓扑排序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列.且该序列必须满足下面两个 ...
- Topological Sorting拓扑排序
定义: Topological Sorting is a method of arranging the vertices in a directed acyclic graph (DAG有向无环图) ...
- Course Schedule课程表12(用Topological Sorting)
[抄题]: 现在你总共有 n 门课需要选,记为 0 到 n - 1.一些课程在修之前需要先修另外的一些课程,比如要学习课程 0 你需要先学习课程 1 ,表示为[0,1]给定n门课以及他们的先决条件,判 ...
- hdu 5195 DZY Loves Topological Sorting (拓扑排序+线段树)
DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 ...
- hdu 5195 DZY Loves Topological Sorting 线段树+拓扑排序
DZY Loves Topological Sorting Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/sho ...
随机推荐
- PIVOT 用于将列值旋转为列名
PIVOT 用于将列值旋转为列名(即行转列),在 SQL Server 2000可以用聚合函数配合CASE语句实现 PIVOT 的一般语法是:PIVOT(聚合函数(列) FOR 列 in (…) )A ...
- 一些需要被禁用的php危险函数
phpinfo() 功能描述:输出 PHP 环境信息以及相关的模块、WEB 环境等信息。 危险等级:中 passthru() 功能描述:允许执行一个外部程序并回显输出,类似于 exec()。 危险等级 ...
- add user
ubuntu adduser deploy usermod -a -G sudo deploy centos adduser deploy passwd deploy usermod -a -G wh ...
- var wi = 0; wi < arr.length; wi++
思维 <?php$w = 123;$wb = $w;$w = 456;echo $wb;?><script type="text/javascript"> ...
- 8 个最佳 PHP 库
PHP标准库 (SPL)的目的就是提供一组接口,让开发者在PHP5中充分利用面向对象编程.因此本文我们搜集了8个最好的,能辅助开发者简化他们的工作,为他们的开发任务服务的PHP库. 如果你喜欢本文,也 ...
- Transform.InverseTransformPoint 反向变换点
JavaScript ⇒ public function InverseTransformPoint(position: Vector3): Vector3; C# ⇒public Vector3 I ...
- 【转】C# 解析JSON方法总结
http://blog.csdn.net/jjhua/article/details/51438317 主要参考http://blog.csdn.NET/joyhen/article/details/ ...
- 使用OC语言编写两个超大数相乘或相加的算法的思路和超大正整数相乘的代码
正文: 在编程中,无论是OC还是C亦或是C++语言,所声明的整数变量都会在内存中占有固定的存储空间,而这些存储空间都是固定的. 比如我们知道的int.long.short.unsigend int.u ...
- Vmware安装与VMware下Linux系统安装
源文件地址:http://www.cnblogs.com/lclq/p/5619271.html 1.下载安装VMware,我安装的是VMware 12.VMware从11开始不再支持32位系统,32 ...
- IIS是如何处理ASP.NET请求的
每次服务器接受到请求,都要先经IIS处理.这不是一篇描述ASP.NE生命周期的文章,仅仅是关于IIS操作的.在我们开始之前,先了解这些会有助于对全文的理解,同时欢迎反馈和建议. 什么是Web Serv ...