2
from collections import defaultdict, deque4
def numBusesToDestination(5
self, routes: List[List[int]], source: int, target: int10
# Creating graph or routes11
graph = defaultdict(set)13
# Since index represents bus_number on a route14
# suppose i is bus number and stops are the values present at that index15
for bus_number, stops in enumerate(routes):16
# for each stop adding buses going to that stop18
graph[stop].add(bus_number)21
bfs = deque([(source, 0)])29
stop, count = bfs.popleft()34
# Since our graph stores all buses going to a stop35
# We will iterate for every bus36
for bus_number in graph[stop]:37
# We dont want to travel in same bus as we might stuck into loop and reach nowhere38
if bus_number not in seen_buses:39
seen_buses.add(bus_number)41
# Now we are in a bus, so we will travel all the stops that bus goes to but again, we only want to go to stops we haven't visited42
for stop in routes[bus_number]:43
if stop not in seen_stops:45
bfs.append((stop, count + 1))