Bus Routes
You are given an array routes where routes[i] is the cyclic list of stops that the i-th bus repeats forever. You start at bus stop source and want to reach bus stop target, traveling only by buses. Return the least number of buses you must take, or -1 if it is impossible. You can board any bus at a stop it serves.
Open official problem prompt ↗Find the minimum number of bus boardings needed to travel from the source stop to the target stop.
Like planning a subway trip counting only line changes: each new line you board costs one, and you want the fewest transfers, not the fewest stations.
- Input
- routes = [[1,2,7],[3,6,7]], source = 1, target = 6
- Output
- 2
- Why
- Take bus 0 from stop 1 to stop 7, then bus 1 from stop 7 to stop 6: two buses.
1 <= routes.length <= 5001 <= sum(routes[i].length) <= 10^5All values of routes[i] are unique within a route0 <= routes[i][j] < 10^60 <= source, target < 10^6