You are given an array routes
representing bus routes where routes[i]
is a bus route that the ith
bus repeats forever.
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
routes[i]
are unique.sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106
This problem can be efficiently solved using Breadth-First Search (BFS). The goal is to find the shortest path (minimum number of buses) from the source
bus stop to the target
bus stop. We represent the bus routes as a graph where bus stops are nodes and edges connect stops that are served by the same bus.
Algorithm:
Initialization:
g
) to store the adjacency list of the graph. The keys are bus stops, and the values are lists of bus route indices that serve that stop.q
) for BFS, initially containing the source
stop and a bus count of 0.visBus
and visStop
) to keep track of visited bus routes and visited bus stops, respectively. This prevents cycles and ensures we find the shortest path.BFS Traversal:
stop
and busCount
.stop
is the target
, return busCount
.buses
) that serve the current stop
(obtained from g
).visBus
):
visBus
).nextStop
) on that bus route.nextStop
:
nextStop
hasn't been visited (visStop
):
nextStop
as visited (visStop
).nextStop
and the incremented busCount
(busCount + 1
) into the queue.No Path:
target
, it means there's no path, so return -1.Time and Space Complexity:
g
), visited sets (visBus
, visStop
), and the queue (q
). The size of these data structures is proportional to the number of routes and stops.Code Examples (Python):
from collections import defaultdict
from collections import deque
def numBusesToDestination(routes, source, target):
if source == target:
return 0
g = defaultdict(list) # Adjacency list: stop -> [bus routes]
for i, route in enumerate(routes):
for stop in route:
g[stop].append(i)
if source not in g or target not in g: # Check if source or target is reachable
return -1
q = deque([(source, 0)]) # (stop, busCount)
visBus = set()
visStop = {source}
while q:
stop, busCount = q.popleft()
if stop == target:
return busCount
for bus in g[stop]:
if bus not in visBus:
visBus.add(bus)
for nextStop in routes[bus]:
if nextStop not in visStop:
visStop.add(nextStop)
q.append((nextStop, busCount + 1))
return -1
The code examples in other languages (Java, C++, Go, TypeScript, C#) provided earlier follow the same algorithmic approach, differing only in syntax and data structure implementations. They all maintain the same time and space complexity.