5 months ago
21 lines573 B
from collections import deque | |
| |
| |
def shortest_path(graph, start, goal): | |
queue = deque([[start]]) | |
seen = {start} | |
while queue: | |
path = queue.popleft() | |
if path[-1] == goal: | |
return path | |
for nxt in graph[path[-1]]: | |
if nxt not in seen: | |
seen.add(nxt) | |
queue.append(path + [nxt]) | |
return None | |
| |
| |
metro = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []} | |
print(shortest_path(metro, "A", "F")) # ['A', 'B', 'D', 'F'] | |
| |
# This is the version we use in the video. |