Topological Sorting 拓扑排序系列题目/课程表/宽度优先

LintCode 127. Topological Sorting

题目链接

给定一个有向图,图节点的拓扑排序定义如下:
对于图中的每一条有向边 A -> B , 在拓扑排序中A一定在B之前.
拓扑排序中的第一个节点可以是图中的任何一个没有其他节点指向它的节点.
针对给定的有向图找到任意一种拓扑排序的顺序.

思路:

首先要找到starting node,也就是in-degree = 0的node。在直接找起点之前,把given的每个node都traverse一遍,并且用一个hashmap记录他们“被neighbor”的次数,也就是他们的in-degree。(第一个循环)

接下来,用另外一个循环, 在map中查找每一个node。如果这个node没有在map中出现过,那么意味着这个node的入度为0,也就是我们需要找的starting node。把这些starting node加入到好基友中(queue q 和arraylsit result)。

最后,BFS搜索,找出一条topologicla sorting的路线。注意:如果一个图有多个starting node,那么[starting node1, starting node2, starting node3, … ]这种排序也是可以的。

/**
 * 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> result = new ArrayList <>();
        HashMap<DirectedGraphNode, Integer> map = new HashMap<>();
        
        //Find all in-degrees
        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);
                }
            }
        }
        
        //Find all starting nodes 
        Queue <DirectedGraphNode> q = new LinkedList<DirectedGraphNode>();
        for(DirectedGraphNode node : graph){
            if(!map.containsKey(node)){
                q.offer(node);
                result.add(node);       //Start populating the result list
            }
        }
        
        //BFS
        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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值