编写程序,演示无向图的遍历操作。要求以邻接矩阵为存储结构实现连通无向图的深度优先遍历和广度优先遍历,输出图的邻接矩阵,并以用户指定的结点为起点,分别输出每种遍历下的结点访问序列和相应生成树的边集。
时间: 2024-12-24 17:28:47 浏览: 1
邻接表或者邻接矩阵为存储结构实现连通无向图的深度优先和广度优先遍历
3星 · 编辑精心推荐
在编写程序时,首先需要创建一个无向图的邻接矩阵表示,这个矩阵是一个二维数组,其中每个元素(i, j)代表节点i和节点j之间是否有边连接。接下来,我们将分别实现深度优先搜索(DFS)和广度优先搜索(BFS)。
**深度优先遍历(DFS):**
```python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(f"从{start}开始的DFS路径: {visited}")
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited
# 示例邻接矩阵
adj_matrix = [[0, 1, 0],
[1, 0, 1],
[0, 1, 0]]
# 指定起点
start_node = int(input("请输入起始节点:"))
dfs(adj_matrix, start_node)
```
**广度优先遍历(BFS):**
```python
from collections import deque
def bfs(graph, start):
visited = set([start])
queue = deque([start])
while queue:
node = queue.popleft()
print(f"从{node}开始的BFS路径: {visited}")
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
bfs(adj_matrix, start_node)
```
**生成树边集:**
对于无向图,我们通常会得到一棵有向生成树,它是连通图的一个子图,其中所有顶点都是可达的,且除了一个顶点外,其他任意两点间只有一条路径。为了获取边集,可以对遍历结果稍作处理:
```python
def get_tree_edges(visited, graph):
tree_edges = []
for i, v in enumerate(visited):
for j in range(len(graph)):
if j != i and graph[i][j] == 1 and j not in visited:
tree_edges.append((v, j))
return tree_edges
start_node = int(input("请输入起始节点:"))
tree_edges_dfs = get_tree_edges(dfs(adj_matrix, start_node), adj_matrix)
tree_edges_bfs = get_tree_edges(bfs(adj_matrix, start_node), adj_matrix)
```
阅读全文