【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;
    }
}
    原文作者:Fokus
    原文地址: https://www.jianshu.com/p/658f80d2b628
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞