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的更多相关文章

  1. hdu.5195.DZY Loves Topological Sorting(topo排序 && 贪心)

    DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 ...

  2. URAL(timus) 1280 Topological Sorting(模拟)

    Topological Sorting Time limit: 1.0 secondMemory limit: 64 MB Michael wants to win the world champio ...

  3. Topological Sorting

    Topological sorting/ ordering is a linear ordering of its vertices such that for every directed edge ...

  4. Union - Find 、 Adjacency list 、 Topological sorting Template

    Find Function Optimization: After Path compression: int find(int x){ return root[x] == x ? x : (root ...

  5. 拓扑排序(Topological Sorting)

    一.什么是拓扑排序 在图论中,拓扑排序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列.且该序列必须满足下面两个 ...

  6. Topological Sorting拓扑排序

    定义: Topological Sorting is a method of arranging the vertices in a directed acyclic graph (DAG有向无环图) ...

  7. Course Schedule课程表12(用Topological Sorting)

    [抄题]: 现在你总共有 n 门课需要选,记为 0 到 n - 1.一些课程在修之前需要先修另外的一些课程,比如要学习课程 0 你需要先学习课程 1 ,表示为[0,1]给定n门课以及他们的先决条件,判 ...

  8. hdu 5195 DZY Loves Topological Sorting (拓扑排序+线段树)

    DZY Loves Topological Sorting Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 ...

  9. hdu 5195 DZY Loves Topological Sorting 线段树+拓扑排序

    DZY Loves Topological Sorting Time Limit: 1 Sec  Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/sho ...

随机推荐

  1. jquery循环绑定事件

    <html> <head> <title></title> <script type="text/javascript" sr ...

  2. Flink - Generating Timestamps / Watermarks

    https://ci.apache.org/projects/flink/flink-docs-release-1.0/apis/streaming/event_timestamps_watermar ...

  3. mysql-zabbix-agent

    使用Zabbix监控MySQL服务器方法 01/27/2014 从Zabbix 2.2开始,Zabbix官方已经支持了MySQL监控,但是MySQL监控默认是不可用的,需要经过额外的设置才可以使用.K ...

  4. zepto源码--qsa--学习笔记

    zepto内部选择器qsa方法的实现. 简述实现原理: 通过判断传入的参数类型: 如果是'#id',则使用getElementById(id)来获取元素,并且将结果包装成数组形式: 如果是'.clas ...

  5. Asset Store

    Asset Store 是用来供Unity开发者将自己的插件拿出来供大家有偿使用的一个平台. 报错信息: failed to import package with error cannot impo ...

  6. 如何将数据库中的表导成XML文件

    1.现将数据库中的信息读到DataTable中 2.用函数将DataTable转为string private string ConvertDataTableToXML(DataTable dt) { ...

  7. Java Binary Tree DFS

    DFS Recursion: public void DFS(TreeNode root){ if(root == null){ return; } System.out.println(root.v ...

  8. iOS:app直播---原理篇

    [如何快速的开发一个完整的iOS直播app](原理篇) 转载自简书@袁峥Seemygo:http://www.jianshu.com/p/7b2f1df74420   一.个人见解(直播难与易) 直播 ...

  9. JavaScript: JavaScript的简介和入门代码演示

    1.Javascript的发展历史介绍: javascript是指的实在网页上编写的编程语言,其主要是控制器html的动态显示效果.HTMl能带来的只是一些基本的页面的风格,而要展示的漂亮使用CSS, ...

  10. Eight Popular Open Source Android Game Engines

    https://software.intel.com/en-us/blogs/2012/05/14/eight-popular-open-source-android-game-engines