深度优先遍历 广度优先遍历的代码示例
时间: 2023-08-14 12:13:56 浏览: 101
广度优先遍历 实例
3星 · 编辑精心推荐
下面是深度优先遍历和广度优先遍历的代码示例(以无向图为例):
深度优先遍历的代码示例:
```python
def dfs(graph, start, visited):
visited.add(start)
print(start, end=' ')
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
# 以邻接表表示图
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
visited = set()
dfs(graph, 'A', visited)
```
广度优先遍历的代码示例:
```python
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=' ')
for neighbor in graph[vertex]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
# 以邻接表表示图
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
bfs(graph, 'A')
```
以上代码示例中,深度优先遍历和广度优先遍历都使用了图的邻接表表示。在深度优先遍历中,使用递归方式实现,通过记录已访问的节点来避免重复访问。在广度优先遍历中,使用队列来存储待访问的节点,并通过记录已访问的节点来避免重复访问。
阅读全文