题目:原题链接(困难)
标签:广度优先搜索
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( R ) O(R) O(R) | O ( R ) O(R) O(R) | 164ms (86.32%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
route_of_stop = collections.defaultdict(list)
for rid, route in enumerate(routes):
for stop in route:
route_of_stop[stop].append(rid)
visited_route = set()
visited_stop = {source}
queue = collections.deque([source])
now = 0
while queue:
for _ in range(len(queue)):
stop1 = queue.popleft()
for rid in route_of_stop[stop1]:
if rid not in visited_route:
for stop2 in routes[rid]:
if stop2 == target:
return now + 1
if stop2 not in visited_stop:
queue.append(stop2)
visited_stop.add(stop2)
visited_route.add(rid)
now += 1
return -1