首页 > 其他 > 详细

[LintCode] Topological Sorting

时间:2015-10-30 07:01:24      阅读:264      评论:0      收藏:0      [点我收藏+]

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:

技术分享

The topological order can be:

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

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

Challenge

Can you do it in both BFS and DFS?

 

SOLUTION :

拓扑排序,这题思路很简单,就是放在图里,显得有些难,首先看这是一个有向图,有向图的就是说不能从任一点开始遍历,一定要找到头,然后拓扑排序如果把它当成树,就有点像level order了,就这么理解一下这个遍历过程就行,是一层一层过去的,每一层的点到开始头的点,距离是一样的。 一看是BFS,肯定用一个queue。

用hash纪录入度的变化,最开始遍历所有的点,然后把neighbors都存下来,看每个neighbor被访问多少次。再第二次遍历所有图,找到没有在图里出现过的点,那个就是头(没有一个点的neighbor指向这个点,所以没在图里出现,所以就是头)。先把这个头加入q跟result里面。第三遍,类似level order,把queue里的点poll出来,然后看这个点的neighbor是谁,然后把图里这个点的value(就是纪录被指向次数的数字) -1,看是不是有value == 0的情况,有就是跟这个头点最近的点,加入q,加入result,然后依次这样操作。

技术分享
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> result = new ArrayList<DirectedGraphNode>();
        HashMap<DirectedGraphNode, Integer> map = new HashMap();
        for (DirectedGraphNode node : graph) {
            for (DirectedGraphNode neighbor : node.neighbors) {
                if (map.containsKey(neighbor)) {
                    map.put(neighbor, map.get(neighbor) + 1);
                } else {
                    map.put(neighbor, 1); 
                }
            }
        }
        Queue<DirectedGraphNode> q = new LinkedList<DirectedGraphNode>();
        for (DirectedGraphNode node : graph) {
            if (!map.containsKey(node)) {
                q.offer(node);
                result.add(node);
            }
        }
        while (!q.isEmpty()) {
            DirectedGraphNode node = q.poll();
            for (DirectedGraphNode n : node.neighbors) {
                map.put(n, map.get(n) - 1);
                if (map.get(n) == 0) {
                    result.add(n);
                    q.offer(n);
                }
            }
        }
        return result;
    }
}
View Code

 

[LintCode] Topological Sorting

原文:http://www.cnblogs.com/tritritri/p/4922268.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!