Explore a graph level by level with a queue of paths, and find the shortest route from A to E.
Python · intermediate · 9 min · 49 steps · free
graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['E'], 'D': ['E'], 'E': []}
def bfs(start, goal):
queue = [[start]]
visited = {start}
while queue:
path = queue.pop(0)
node = path[-1]
if node == goal:
return path
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(path + [neighbor])
return None
print(bfs('A', 'E'))bfs(). Its body does not run yet: it runs each time the function is called.bfs(), with start = 'A' and goal = 'E'. It gets its own names.visited is created and points to a new set: ['A'].queue is true, so the loop body runs.path is created and points to a new list: ['A']. a list is removed from the end of the list that queue points to.node is created with the value 'A'.node == goal is false, so the block under it is skipped.neighbor is created with the value 'B'.neighbor not in visited is true, so the block under it runs.visited points to.neighbor changes from 'B' to 'C'.neighbor not in visited is true, so the block under it runs.visited points to.queue points to.for neighbor in graph[node].queue is true, so the loop body runs.node changes from 'A' to 'B'.node == goal is false, so the block under it is skipped.neighbor changes from 'C' to 'D'.neighbor not in visited is true, so the block under it runs.visited points to.queue points to.for neighbor in graph[node].queue is true, so the loop body runs.path now points to a different list: ['A', 'C']. a list is removed from the start of the list that queue points to.node changes from 'B' to 'C'.node == goal is false, so the block under it is skipped.neighbor changes from 'D' to 'E'.neighbor not in visited is true, so the block under it runs.visited points to.queue points to.for neighbor in graph[node].queue is true, so the loop body runs.path now points to a different list: ['A', 'B', 'D']. a list is removed from the start of the list that queue points to.node changes from 'C' to 'D'.node == goal is false, so the block under it is skipped.for neighbor in graph[node].neighbor not in visited is false, so the block under it is skipped.for neighbor in graph[node].queue is true, so the loop body runs.path now points to a different list: ['A', 'C', 'E']. a list is removed from the end of the list that queue points to.node changes from 'D' to 'E'.path.bfs() has finished, so its names are gone. It prints ['A', 'C', 'E'].Answer: Queue
visited?Answer: To avoid going round in circles
← Heaps and Priority Queues · Depth-First Search →