| #BFS
|
| from collections import deque
|
|
|
| graph = {
|
| 'A': ['B', 'F', 'I'],
|
| 'B': ['A', 'C', 'E'],
|
| 'C': ['B', 'D', 'E'],
|
| 'D': ['C', 'G', 'H'],
|
| 'E': ['B', 'C', 'G'],
|
| 'F': ['A', 'G'],
|
| 'G': ['E', 'F', 'D'],
|
| 'H': ['D'],
|
| 'I': ['A']
|
| }
|
|
|
| def bfs(graph, start_node):
|
| visited = set()
|
| queue = deque([start_node])
|
|
|
| while queue:
|
| node = queue.popleft()
|
|
|
| if node in visited:
|
| continue
|
| visited.add(node)
|
| print(node, end=' ')
|
|
|
| for st in graph[node]:
|
| if st not in visited:
|
| queue.append(st)
|
|
|
| bfs(graph, 'A')
|