码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Topological Sorting

时间:2016-04-07 12:04:53      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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]
...
Challenge

Can you do it in both BFS and DFS?

 

/**
 * 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
        
        if(graph == null || graph.size() == 0)
            return graph;
        
        ArrayList<DirectedGraphNode> res = new ArrayList<DirectedGraphNode>();
        HashMap<DirectedGraphNode, Integer> map = new HashMap<DirectedGraphNode, Integer>();
        
        for(DirectedGraphNode node: graph)
            map.put(node, 0);
        
        for(DirectedGraphNode node: graph){
            for(DirectedGraphNode n: node.neighbors){
                    map.put(n, map.get(n) + 1);
            }
        }
        
        DirectedGraphNode start = null;
        Queue<DirectedGraphNode> queue = new LinkedList<DirectedGraphNode>();
        
        for(DirectedGraphNode temp: graph){
            if(map.get(temp) == 0){
                start = temp;
                queue.offer(start);
                res.add(start);
            }
        }
        
        while(!queue.isEmpty()){
            DirectedGraphNode temp = queue.poll();
            
            for(DirectedGraphNode n: temp.neighbors){
                map.put(n, map.get(n) - 1);
                
                if(map.get(n) == 0){
                    queue.offer(n);
                    res.add(n);
                }
            }
        }
        
        return res;
    }
}

 

lintcode-medium-Topological Sorting

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5362916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!