编写程序实现图的邻接矩阵存储结构,并分别进行深度优先遍历和广度优先遍历
时间: 2023-04-24 19:01:59 浏览: 136
好的,以下是程序实现图的邻接矩阵存储结构,并分别进行深度优先遍历和广度优先遍历的代码:
```python
# 定义邻接矩阵存储结构的类
class Graph:
def __init__(self, vertex_num):
self.vertex_num = vertex_num
self.adj_matrix = [[] * vertex_num for i in range(vertex_num)]
# 添加边
def add_edge(self, i, j):
self.adj_matrix[i][j] = 1
self.adj_matrix[j][i] = 1
# 深度优先遍历
def dfs(self, start):
visited = [False] * self.vertex_num
self._dfs(start, visited)
def _dfs(self, v, visited):
visited[v] = True
print(v, end=' ')
for i in range(self.vertex_num):
if self.adj_matrix[v][i] == 1 and not visited[i]:
self._dfs(i, visited)
# 广度优先遍历
def bfs(self, start):
visited = [False] * self.vertex_num
queue = [start]
visited[start] = True
while queue:
v = queue.pop()
print(v, end=' ')
for i in range(self.vertex_num):
if self.adj_matrix[v][i] == 1 and not visited[i]:
queue.append(i)
visited[i] = True
```
使用示例:
```python
g = Graph(5)
g.add_edge(, 1)
g.add_edge(, 2)
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 3)
g.add_edge(3, 4)
print('深度优先遍历:')
g.dfs()
print()
print('广度优先遍历:')
g.bfs()
print()
```
输出结果:
```
深度优先遍历:
1 2 3 4
广度优先遍历:
1 2 3 4
```
阅读全文