bfs
Mon Jan 06 2025 18:07:15 GMT+0000 (Coordinated Universal Time)
Saved by
@viinod07
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [],
'E': [],
'F': [],
'G': []
}
def bfs(graph, start, goal):
visited = [] # List to keep track of visited nodes
queue = [] # Queue for BFS
visited.append(start)
queue.append(start)
while queue:
s = queue.pop(0) # Dequeue a node
if s == goal: # Stop as soon as the goal is found
print(s)
return
print(s) # Print the current node
for neighbor in graph[s]:
if neighbor not in visited:
visited.append(neighbor)
queue.append(neighbor)
# Call the function
bfs(graph, 'A', 'F')
content_copyCOPY
Comments