无向图的深度优先遍历和广度优先遍历是否唯一
时间: 2023-11-22 22:49:14 浏览: 357
图的深度优先遍历及广度优先遍历
无向图的深度优先遍历和广度优先遍历不一定唯一,因为在遍历时可能存在多个未访问的节点可以选择,而不同的选择顺序可能会导致不同的遍历结果。但是,对于同一张无向图,无论采用哪种遍历方式,最终都会遍历到所有的节点。
以下是无向图深度优先遍历和广度优先遍历的Python实现:
1.深度优先遍历
```python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next_node in graph[start] - visited:
dfs(graph, next_node, visited)
return visited
# 示例
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
dfs(graph, 'A')
```
输出结果为:A B D E F C
2.广度优先遍历
```python
from collections import deque
def bfs(graph, start):
visited, queue = set(), deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex)
for next_node in graph[vertex] - visited:
visited.add(next_node)
queue.append(next_node)
# 示例
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
bfs(graph, 'A')
```
输出结果为:A B C D E F
阅读全文