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: 2Explanation: 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: -1Constraints:
1 <= routes.length <= 5001 <= routes[i].length <= 1,00,000routes[i] are unique.sum(routes[i].length) <= 1,00,0000 <= routes[i][j] < 1,000,0000 <= source, target < 1,000,000class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
n = len(routes)
stops = defaultdict(list)
for bus in range(n):
for stop in routes[bus]:
stops[stop].append(bus)
seen_bus = set()
seen_stop = set([source])
res = 0
q = deque([source])
while q:
for _ in range(len(q)):
stop = q.popleft()
if stop == target:
return res
for bus in stops[stop]:
if bus in seen_bus:
continue
seen_bus.add(bus)
for nxtStop in routes[bus]:
if nxtStop in seen_stop:
continue
seen_stop.add(nxtStop)
q.append(nxtStop)
res += 1
return -1Where is the number of routes and is the maximum number of stops per bus route.
class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
n = len(routes)
adjList = [[] for _ in range(n)]
stopToRoutes = defaultdict(list)
for bus, route in enumerate(routes):
for stop in route:
stopToRoutes[stop].append(bus)
if target not in stopToRoutes or source not in stopToRoutes:
return -1
hasEdge = [[False] * n for _ in range(n)]
for buses in stopToRoutes.values():
for i in range(len(buses)):
for j in range(i + 1, len(buses)):
if hasEdge[buses[i]][buses[j]]:
continue
hasEdge[buses[i]][buses[j]] = True
hasEdge[buses[j]][buses[i]] = True
adjList[buses[i]].append(buses[j])
adjList[buses[j]].append(buses[i])
q = deque([node for node in stopToRoutes[source]])
res = 1
while q:
for _ in range(len(q)):
node = q.popleft()
if node in stopToRoutes[target]:
return res
while adjList[node]:
nxtBus = adjList[node].pop()
if adjList[nxtBus]:
q.append(nxtBus)
res += 1
return -1Where is the number of routes and is the maximum number of stops per bus route.