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 ...
随机推荐
- delimiter
http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx The first command is ...
- 不要让mysql犹豫不决
DROP TABLE IF EXISTS `w1`; CREATE TABLE `w1` ( `waid` ) NOT NULL AUTO_INCREMENT, `wa1` ) COLLATE utf ...
- ArcGIS Server 缓存服务增加新比例尺缓存
win10 + Server 10.4 + ArcMap 10.4 操作简单说明: ①窗口上方Customize栏→Toolbars→ Customize→ 搜索到 manege map serv ...
- 【转】说说如何使用unity Vs来进行断点调试
大家可以从这下载最新版的unity vs. UnityVs1.81下载 1. 安装unity vs.首先我们打开我们下载的unity vs.然后就会看见里面有3个文件,我们双击UnityVS 2 ...
- ubuntu12.04 安装 php5.4/php5.5
1:修改源(我使用163的源)直接修改/etc/apt/sources.list deb http://mirrors.163.com/ubuntu/ precise main universe re ...
- 阻止默认行为stopDefault
function stopDefault(e){ if(e && e.preventDefault) e.preventDefault(); else window.event.ret ...
- Archiver 浅析
归档是一个过程,即用某种格式来保存一个或多个对象,以便以后还原这些对象.通常,这个过程包括将(多个)对象写入文件中,以便以后读取该对象. 两种归档数据的方法:属性列表和带键值的编码. 属性列表局限性很 ...
- There is no tracking information for the current branch
There is no tracking information for the current branch. Please specify which branch you want to mer ...
- ArcGIS Engine开发的ArcGIS 版本管理的功能
原文:ArcGIS Engine开发的ArcGIS 版本管理的功能 转自:http://blog.csdn.net/linghe301/article/details/7965901 这是以前的Arc ...
- [LeetCode]题解(python):078 Subsets
题目来源 https://leetcode.com/problems/subsets/ Given a set of distinct integers, nums, return all possi ...
The topological order can be:
[0, 1, 2, 3, 4, 5]
or
[0, 2, 3, 1, 5, 4]
or
....
Challenge