fork download
  1. graph = {'A': ['B', 'C', 'E'],
  2. 'B': ['A','D', 'E'],
  3. 'C': ['A', 'F', 'G'],
  4. 'D': ['B'],
  5. 'E': ['A', 'B','D'],
  6. 'F': ['C'],
  7. 'G': ['C']}
  8. def bfs(graph, initial):
  9. visited = []
  10. queue = [initial]
  11. while queue:
  12. node = queue.pop(0)
  13. if node not in visited:
  14. visited.append(node)
  15. neighbours = graph[node]
  16. for neighbour in neighbours:
  17. queue.append(neighbour)
  18. return visited
  19. print(bfs(graph,'A'))
Success #stdin #stdout 0.04s 9132KB
stdin
Standard input is empty
stdout
['A', 'B', 'C', 'E', 'D', 'F', 'G']