Bus Routes

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.

Constraints:

  • 1 <= routes.length <= 500.

  • 1 <= routes[i].length <= 10^5.

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

class Solution {
    public int numBusesToDestination(int[][] routes, int S, int T) {
        if (S == T)
            return 0;
        // Graph of cycles
        Set<Integer>[] graph = new HashSet[routes.length];
        for (int i = 0; i < routes.length; i++)
            graph[i] = new HashSet<>();
        // dest -> cycle list
        HashMap<Integer, Set<Integer>> map = new HashMap<>();
        for (int i = 0; i < routes.length; i++) {
            for (int x : routes[i]) {
                if (!map.containsKey(x))
                    map.put(x, new HashSet<>());
                for (int cycle : map.get(x)) {
                    if (cycle != i) {
                        graph[i].add(cycle);
                        graph[cycle].add(i);
                    }
                }
                map.get(x).add(i);
            }
        }
        int count = 1;
        boolean[] visited = new boolean[routes.length];
        Queue<Integer> q = new LinkedList<>();
        for (int x : map.get(S))
            q.add(x);
        while (q.size() != 0) {
            int size = q.size();
            while (size-- > 0) {
                int cycle = q.poll();
                visited[cycle] = true;
                if (map.get(T).contains(cycle))
                    return count;
                for (int neighborCycle : graph[cycle])
                    if (!visited[neighborCycle])
                        q.add(neighborCycle);
            }
            count++;
        }
        return -1;
    }
}

Last updated