Bus Routes - Problem
You are given an array routes representing bus routes where 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 0-th 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.
Input & Output
Example 1 — Basic Transfer
$
Input:
routes = [[1,2,7],[3,6,7]], source = 1, target = 6
›
Output:
2
💡 Note:
Take Bus 0 from stop 1 to stop 7, then transfer to Bus 1 from stop 7 to reach stop 6. Total: 2 buses.
Example 2 — Direct Route
$
Input:
routes = [[7,12],[4,5,15],[6],[15,19,26,7]], source = 15, target = 12
›
Output:
-1
💡 Note:
No possible route from stop 15 to stop 12. Bus 1 contains 15, Bus 0 contains 12, but they don't share any common stops.
Example 3 — Same Stop
$
Input:
routes = [[1,2,7],[3,6,7]], source = 6, target = 6
›
Output:
0
💡 Note:
Already at target stop, no buses needed.
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
Visualization
Tap to expand
Understanding the Visualization
1
Input
Bus routes and source/target stops
2
Process
Find minimum bus transfers using BFS
3
Output
Minimum number of buses needed
Key Takeaway
🎯 Key Insight: Think in terms of buses as graph nodes rather than individual stops - BFS on buses finds optimal transfer count
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code