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.

Example

For graph as follow:

picture

The topological order can be:

[0, 1, 2, 3, 4, 5]
[0, 2, 3, 1, 5, 4]
...
题目的要求是被指向的节点要在指向它的节点后出现。如何实现该功能, 可以纪录该节点被指向的数目, 每加入一个指向它的节点到result中时,就将该节点的被指向数减1.
思路:定义一个HashMap 用于记录当前结点被几个节点所指向。 将没有被其他节点指向的节点加入到result中,同时加入到一个队列中,依次取出队列中的节点,在HashMap中查找该节点所指向的节点,将其value - 1 ,
    当value == 0 时,表明该节点已经没有被任何节点指向(指向它的节点都已经加入到result中),所有可以将该节点加入到result 中, 被加入到queue中。
 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         ArrayList<DirectedGraphNode> result = new ArrayList<>();
16         HashMap<DirectedGraphNode, Integer> map = new HashMap<>();
17         for (DirectedGraphNode node : graph) {
18             for (DirectedGraphNode neighbor : node.neighbors) {
19                 if (map.containsKey(neighbor)) {
20                     map.put(neighbor, map.get(neighbor) + 1);
21                 } else {
22                     map.put(neighbor, 1);
23                 }
24             }
25         }
26         Queue<DirectedGraphNode> queue = new LinkedList<>();
27         for (DirectedGraphNode node : graph) {
28             if (!map.containsKey(node)) {
29                 queue.offer(node);
30                 result.add(node);
31             }
32         }
33         while (!queue.isEmpty()) {
34             DirectedGraphNode node = queue.poll();
35             for (DirectedGraphNode neighbor : node.neighbors) {
36                 map.put(neighbor, map.get(neighbor) - 1);
37                 if (map.get(neighbor) == 0) {
38                     result.add(neighbor);
39                     queue.offer(neighbor);
40                 }
41             }
42         }
43         return result;
44     }
45 }

 

posted @ 2016-04-29 16:36  YuriFLAG  阅读(189)  评论(0)    收藏  举报