You're planning a journey through a complex city bus system! π
You have an array routes where each routes[i] represents the stops that bus i visits in order. Each bus follows its route in a circular pattern forever. For example, if routes[0] = [1, 5, 7], then bus 0 travels: 1 β 5 β 7 β 1 β 5 β 7 β ... infinitely.
You start at bus stop source (not on any bus initially) and want to reach bus stop target. You can only travel by taking buses - no walking between stops!
Goal: Find the minimum number of buses you need to take to get from source to target. Return -1 if it's impossible.
Think of this as finding the shortest path in a graph where nodes are bus stops and edges represent bus connections! π―
Input & Output
Visualization
Time & Space Complexity
N is total number of stops across all routes, M is number of bus routes. Each stop is processed at most once per bus route
Space for stop-to-buses mapping (N) and BFS queue/visited set (M)
Constraints
- 1 β€ routes.length β€ 500
- 1 β€ routes[i].length β€ 105
- All values of routes[i] are unique
- Sum of routes[i].length β€ 105
- 0 β€ routes[i][j] β€ 106
- 0 β€ source, target β€ 106