Bus Routes
Problem statement
You are given an array routes, where routes[i] lists the bus stops that bus i visits. Each bus drives its route in a loop forever, so once you are on bus i, you can ride it to any stop in routes[i].
You start at bus stop source and you are not on a bus yet. You want to reach bus stop target. You can travel only by bus, and you can change from one bus to another at any stop that both buses visit.
Return the least number of buses you must take to reach target. Return -1 if you cannot reach it. If source equals target, return 0, because you are already there.
Function
numBusesToDestination(routes: int[][], source: int, target: int) → intExamples
Example 1
routes = [[2,5,9],[9,4,1],[1,8,3],[6,7]]source = 5target = 3return = 3Take bus 0 from stop 5 to stop 9. Change to bus 1 and ride it to stop 1. Change to bus 2 and ride it to stop 3. That is 3 buses.
No single bus or pair of buses works. Only bus 0 stops at 5, and it shares a stop only with bus 1, which does not stop at 3.
Example 2
routes = [[2,5,9],[9,4,1],[1,8,3],[6,7]]source = 5target = 7return = -1Stop 7 is only on bus 3, and bus 3 shares no stop with any other bus. You can never get on it from stop 5, so the answer is -1.
Example 3
routes = [[2,5,9]]source = 11target = 11return = 0You are already at stop 11, so you need 0 buses. It does not matter that no bus stops there.
Constraints
1 <= routes.length <= 5001 <= routes[i].length <= 10^4- The total number of stops in all routes is at most
10^4. - The stops in each
routes[i]are all different. 0 <= routes[i][j] < 10^60 <= source, target < 10^6