给定一个无向连通图G,采用深度优先搜索方式访问图中节点,并输出。
时间: 2024-06-13 09:08:28 浏览: 125
以下是基于邻接表的深度优先搜索遍历无向连通图的Python实现:
```python
# 定义图类
class Graph:
def __init__(self, vertices):
self.V = vertices # 节点数
self.adj = [[] for i in range(vertices)] # 邻接表
# 添加边
def add_edge(self, u, v):
self.adj[u].append(v)
self.adj[v].append(u)
# 深度优先搜索遍历
def DFS(self, v, visited):
visited[v] = True
print(v, end=' ')
for i in self.adj[v]:
if not visited[i]:
self.DFS(i, visited)
# 遍历图
def traverse(self, start):
visited = [False] * self.V
if start in range(self.V):
self.DFS(start, visited)
else:
print("起点不在图中!")
```
以下是基于邻接矩阵和队列的广度优先搜索遍历无向连通图的Python实现:
```python
# 定义图类
class Graph:
def __init__(self, vertices):
self.V = vertices # 节点数
self.adj = [[0] * vertices for i in range(vertices)] # 邻接矩阵
# 添加边
def add_edge(self, u, v):
self.adj[u][v] = 1
self.adj[v][u] = 1
# 广度优先搜索遍历
def BFS(self, v, visited):
queue = []
visited[v] = True
queue.append(v)
while queue:
v = queue.pop(0)
print(v, end=' ')
for i in range(self.V):
if self.adj[v][i] == 1 and not visited[i]:
visited[i] = True
queue.append(i)
# 遍历图
def traverse(self, start):
visited = [False] * self.V
if start in range(self.V):
self.BFS(start, visited)
else:
print("起点不在图中!")
```
调用示例:
```python
# 创建图
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 3)
g.add_edge(3, 4)
# 深度优先搜索遍历
print("深度优先搜索遍历:")
g.traverse(0)
print()
# 广度优先搜索遍历
print("广度优先搜索遍历:")
g.traverse(0)
print()
```
阅读全文