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 ...
随机推荐
- 【转载】C内存分配
一.预备知识—程序的内存分配 一个由C/C++编译的程序占用的内存分为以下几个部分 1.栈区(stack)— 由编译器自动分配释放,存放函数的参数值,局部变量的值等.其操作方式类似于数据结构中的栈. ...
- Delphi结构体数组指针的问题
//这段代码在Delphi 2007和delphi 7下是可以执行的,所以正确使用结构体数组和指针应该是这样的,已验证 unit Unit1; interface uses Windows, Mess ...
- c语言学习上的思考与心得
由于这段时间在c语言的学习中,表现的很努力并且完成作业态度认真,所以得到了老师奖励的小黄衫. 以下是我对于c语言的学习感受与心得. 学习感受与心得 我选择计算机的这个专业,是因为我对计算机的学习很有兴 ...
- AppleScript
一.资源 1.书本 2.ide: AppleSreipt Editor 3.界面辅助软件: UIBrowser 破解方法: a) ui browser -> show package conte ...
- CDH(Cloudera)与hadoop(apache)对比
本文出自:CDH(Cloudera)与hadoop(apache)对比http://www.aboutyun.com/thread-9225-1-1.html(出处: about云开发) 问题导读 ...
- 树莓派如何便捷的使用pi4j
问题的由来 pi4j用起来很方便,但是感觉pi4j库的命名太杂乱,啰嗦了,很容易弄混,而且好像没听说官方有自己的编译器.如果没有智能点的编辑器的话,写起来真要命,但是树莓派运行Eclipse不太现实, ...
- yii2 实现多表联查
- Python排列组合实验
import itertools 排列: 4个数内选2个 >>> print list(itertools.permutations([1,2,3,4],2)) [(1, 2), ( ...
- 算法训练 Hankson的趣味题
算法训练 Hankson的趣味题 时间限制:1.0s 内存限制:64.0MB 问题描述 Hanks 博士是BT (Bio-Tech,生物技术) 领域的知名专家,他的儿子名叫Han ...
- [LeetCode] Combinations (bfs bad、dfs 递归 accept)
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For exampl ...