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.

Solutions

1. BFS

# Time: O(nlogn)
# Space: O(n)
class Solution:
    def numBusesToDestination(self, routes: List[List[int]], S: int, T: int) -> int:
        if S == T:
            return 0
        stop_board = collections.defaultdict()
        for bus, stops in enumerate(routes):
            for stop in stops:
                if stop not in stop_board:
                    stop_board[stop] = [bus]
                else:
                    stop_board[stop].append(bus)
        queue = collections.deque([S])
        visited = set()

        res = 0
        while queue:
            res += 1
            size_stops_reach = len(queue)
            for _ in range(size_stops_reach):
                cur_stop = queue.popleft()
                for bus in stop_board[cur_stop]:
                    if bus in visited:
                        continue
                    visited.add(bus)
                    for stop in routes[bus]:
                        if stop == T:
                            return res
                        queue.append(stop)
        return -1
# 45/45 cases passed (392 ms)
# Your runtime beats 92 % of python3 submissions
# Your memory usage beats 100 % of python3 submissions (31.6 MB)

References

  1. 815. Bus Routes