815. Bus Routes

Question

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. 1 <= routes.length <= 500.
  2. 1 <= routes[i].length <= 500.
  3. 0 <= routes[i][j] < 10 ^ 6.

Solution

  • Method 1: bfs
    • we need to construct a graph using map, where key is the stop number and value is a list recording all buses passes through this stop.
    • we also need a boolean array to record which bus is visited since all stops on this routes can be visited.
      class Solution {
        public int numBusesToDestination(int[][] routes, int S, int T) {
            if(S == T) return 0;
            // Create the graph
            Map<Integer, List<Integer>> g = new HashMap<>();
            for(int i = 0; i < routes.length; i++){
                for(int j = 0; j < routes[i].length; j++){
                    List<Integer> buses = g.containsKey(routes[i][j]) ? g.get(routes[i][j]): new ArrayList<>();
                    buses.add(i);
                    g.put(routes[i][j], buses);
                }
            }
            Queue<Integer> q = new LinkedList<>();
            q.offer(S);
            int step = 0;
            boolean[] ride = new boolean[routes.length];
            while(!q.isEmpty()){
                int size = q.size();
                ++step;
                for(int i = 0; i < size; i++){
                    int cur = q.poll();
                    // for each bus stop, get all buses that can pass through this stop
                    List<Integer> buses = g.get(cur);
                    for(Integer bus : buses){
                        if(ride[bus]) continue;
                        ride[bus] = true;
                        // If never visited this bus before, add all stops of this bus to the queue.
                        for(Integer stop : routes[bus]){
                            if(stop == T) return step;
                            q.offer(stop);
                        }
                    }
                }
            }
            return -1;
        }
      }
      

Reference

  1. 花花酱 LeetCode 815. Bus Routes