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.

 Notice

You can assume that there is at least one topological order in the graph.

Clarification

Learn more about representation of graphs

 1 /**
 2  * Definition for Directed graph.
 3  * class DirectedGraphNode {
 4  *     int label;
 5  *     ArrayList<DirectedGraphNode> neighbors;
 6  *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 7  * };
 8  */
 9 public class Solution {
10     /**
11      * @param graph: A list of Directed graph node
12      * @return: Any topological order for the given graph.
13      */    
14     public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
15         
16         ArrayList<DirectedGraphNode> result = new ArrayList<DirectedGraphNode>();
17         HashMap<DirectedGraphNode, Integer> map = new HashMap();
18         // put all neighbors in the map
19         for (DirectedGraphNode node : graph) {
20             for (DirectedGraphNode neighbor : node.neighbors) {
21                 if (map.containsKey(neighbor)) {
22                     map.put(neighbor, map.get(neighbor) + 1);
23                 } else {
24                     map.put(neighbor, 1); 
25                 }
26             }
27         }
28         Queue<DirectedGraphNode> q = new LinkedList<DirectedGraphNode>();
29         // 找出root节点
30         for (DirectedGraphNode node : graph) {
31             if (!map.containsKey(node)) {
32                 q.offer(node);
33                 result.add(node);
34             }
35         }
36         
37         while (!q.isEmpty()) {
38             DirectedGraphNode node = q.poll();
39             for (DirectedGraphNode n : node.neighbors) {
40                 map.put(n, map.get(n) - 1);
41                 if (map.get(n) == 0) {
42                     result.add(n);
43                     q.offer(n);
44                 }
45             }
46         }
47         return result;
48     }
49 }

 

 

 

Example

For graph as follow:

picture

The topological order can be:

[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...

分析:
为了保证下面一点:
  • For each directed edge A -> B in graph, A must be before B in the order list.
我们需要确定B的parent node已经被取出了,关键是怎么知道B的parent nodes都已经加进去了呢?这里用了hashmap,那个值就是parent node的个数,一旦parent node被取出,就把那个值减一。


posted @ 2016-07-22 09:56  北叶青藤  阅读(193)  评论(0编辑  收藏  举报