LC815 - Bus Routes

Description

You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.
For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> … forever.
You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.
Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.

Example 1:
Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 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.

Example 2:
Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
Output: -1
Constraints:
1 <= routes.length <= 500.
1 <= routes[i].length <= 105
All the values of routes[i] are unique.
sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106

Solution

  • HashSet + BFS
  • we consider the index of the routes as the bus number, for each bus, we have several stops
  • we store the stops as the key, and the bus number as the value into the stops_hash. We also make each bus’ stops into a set as bus_set
  • for the stops in one bus, we don’t need to worry about how many buses we need to transit. Therefore, we append the unvisited stops into the bus and the step +1. In this case, all the stops in one bus will have the same steps.
  • when the current stop equals target, we return steps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from collections import deque
class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
stops_hash = {}
buses_set = []
for idx, value in enumerate(routes):
buses_set.append(set(value))
for v in value:
if v not in stops_hash:
stops_hash[v] = set({idx})
else:
stops_hash[v].add(idx)
# {1: {0}, 2: {0}, 7: {0, 1}, 3: {1}, 6: {1}}
# [{1, 2, 7}, {3, 6, 7}]

queue = deque([(source, 0)])
bus_visited = set()
stop_visited = set({source})
while queue:
cur_stop, step = queue.popleft()
if cur_stop == target:
return step

for bus in stops_hash[cur_stop] - bus_visited:
for stop in buses_set[bus] - stop_visited:
bus_visited.add(bus)
stop_visited.add(stop)
queue.append((stop, step+1))
return -1