图的广度优先遍历与深度优先遍历数据结构代码实现
时间: 2023-06-21 21:11:27 浏览: 112
C/C++实现图的深度优先遍历和广度优先遍历
广度优先遍历(BFS):
```python
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
```
深度优先遍历(DFS):
```python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for next_vertex in graph[start] - visited:
dfs(graph, next_vertex, visited)
return visited
```
其中,`graph` 是一个字典,表示图的邻接表。例如,如果有一条边从节点 `A` 连接到节点 `B`,则在邻接表中,`graph['A']` 中会包含 `'B'`。
阅读全文