美文网首页数据结构
Leetcode: 815 公交路线

Leetcode: 815 公交路线

作者: TimberTang | 来源:发表于2019-08-12 11:01 被阅读0次

https://leetcode-cn.com/submissions/detail/25642457/

class Solution {
    public int numBusesToDestination(int[][] routes, int S, int T) {
        if (S == T) { // 如果起点 == 终点 return
            return 0;
        } 
        
        // 根据公交车节点和公交站点节点建立关系
        Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
        for (int i = 0; i< routes.length; ++ i) {
            for (int j: routes[i]) { // j  = 公交站点
                if (!map.containsKey(j)) { // 不包含的公交站点则加入 map
                    map.put(j, new HashSet<Integer>()); // 默认初始值为0
                }
                map.get(j).add(i);
            }
        }
        
        // 从起点开始, 吧所有符合公交车站点节点S的对应公交车加入queue中
        Queue<Integer> queue = new LinkedList<Integer>();
        Set<Integer> visited = new HashSet<Integer>();
        for (int st: map.get(S)) {
            queue.offer(st);
            visited.add(st);
        }
        
        int ans = 1;
        
        while(!queue.isEmpty()) {// 知道队列为空
            Queue<Integer> t = new LinkedList<Integer>();
            while(!queue.isEmpty()) {
                int currentCar = queue.poll();
                for (int k: routes[currentCar]) {// 遍历链接的公交车站节点
                    if (k == T) {
                        return ans;
                    }
                    for (int nextCar : map.get(k)) { // 便利当前公交车站点所有的公交车借点
                        if (!visited.contains(nextCar)) {// 未访问过的
                            t.offer(nextCar);
                            visited.add(nextCar);
                        }
                    }
                }
            }
            ++ ans;
            queue = t;
        }
        
        return -1;
        
    }
}

相关文章

  • Leetcode: 815 公交路线

    https://leetcode-cn.com/submissions/detail/25642457/

  • LeetCode-python 815.公交路线

    题目链接难度:困难 类型: 广度优先搜索 我们有一系列公交路线。每一条路线 routes[i]...

  • 815. 公交路线

    注意层次遍历,队列会动态增加

  • 815

    慵懒的一天,早晨在梦里真的很伤心打电话给他最后竟然关机了,还是有点不开心,但是还是喜欢开着视频看他工作,听着他那边...

  • 815

  • 815

    下午能量补足,晚上出门运气爆棚,加油,从自律开始~

  • 815

    日头出来点点红照进妹房米海空米海越空越好耍只愁命短不愁穷 一条江水去悠悠一朵莲花水面浮何时有心把花起你无心无意看花...

  • 815

    夏天还有个尾巴,秋天很短命,最好的是冬日,快乐不假借外物,语言退回嘴巴,温度退回身体,大雪弥漫,不关心除了阳光之外...

  • 815

    人安逸下来就很多事都不会太过在乎,或计较,安心眼下的生活,不会太想以后。我想要自己时刻保持清醒,可是很难,一忙下来...

  • 815

    12月23日,冬月二十,多云,周四 下午下班开单元门,听到一墙之隔的隔壁小区,有放哀乐的声音,看来是有老人去世了。...

网友评论

    本文标题:Leetcode: 815 公交路线

    本文链接:https://www.haomeiwen.com/subject/vimyjctx.html