【Leecode】815. Bus Routes

Description

We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.

We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.


Example:
Input: 
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6

Output: 2
Explanation: 
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.

Note:

  • 1 <= routes.length <= 500.
  • 1 <= routes[i].length <= 500.
  • 0 <= routes[i][j] < 10 ^ 6.

Discuss

使用广度遍历。首先把每一站的可达bus数存起来,也就是把每一站出现的行存起来。然后从起始站开始,把可达的每一个bus站都存入队列,依次遍历,一直到最后的终点站结束。

Code

class Solution {
    public int numBusesToDestination(int[][] routes, int S, int T) {
        HashSet<Integer> visited = new HashSet<>();
        Queue<Integer> q = new LinkedList<>();
        Map<Integer, ArrayList<Integer>> map = new HashMap<>();
        
        int res = 0;
        if (S == T) { return 0; }
        
        for (int i = 0; i < routes.length; i++) {
            for (int j = 0; j < routes[0].length; j++) {
                //把每一站出现的行记录下来,如{[1,2,7],[3,6,7]}中,7出现了两次,就把0,1添加进list中
                ArrayList<Integer> list = map.getOrDefault(routes[i][j], new ArrayList<Integer>());
                list.add(i);
                map.put(routes[i][j], list);
            }
        }
        
        q.offer(S);
        while (!q.isEmpty()) {
            //所有与S相连的元素的个数
            int len = q.size();
            res++;
            for (int i = 0; i < len; i++) {
                int s = q.poll();
                ArrayList<Integer> list = map.get(s);
                for (int bus : list) {
                    if (visited.contains(bus)) continue;
                    visited.add(bus);
                    for (int j = 0; j < routes[bus].length; j++) {
                        if (routes[bus][j] == T) return res;
                        q.offer(routes[bus][j]);
                    }
                }
            }
        }
        return -1;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • 我迷茫到不行。怀疑自己得了抑郁症。 突然觉得大学没有前景。我连他妈去都不想去。
    注视你背影投射出的温柔阅读 1,576评论 0 2
  • 简单地读一本书的时候,很多段落只是滑过,事后不会留有任何印象。而整本书读完,也只能记得大概。如果是历史书或小说,可...
    三角猫阅读 3,411评论 5 13
  • 姓名:常洪洋 (单位)大庆油田第五采油厂机关人事部(组织部) 【日精进打卡第 14 天】打卡日期:2018年4月7...
    翱翔九天_4a06阅读 1,319评论 0 0

友情链接更多精彩内容