设无向图G有n个顶点(设顶点值用1~n编号),m条边,假设图以数组表示法存储。 编写程序,实现以下功能: (1)创建图的邻接矩阵存储结构 (2)深度优先遍历 (3)广度优先遍历
时间: 2023-12-03 22:47:05 浏览: 83
以下是 Python 代码实现:
```python
class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.adj_matrix = [[0] * num_vertices for _ in range(num_vertices)]
def add_edge(self, i, j):
self.adj_matrix[i][j] = 1
self.adj_matrix[j][i] = 1
def remove_edge(self, i, j):
self.adj_matrix[i][j] = 0
self.adj_matrix[j][i] = 0
def depth_first_search(self, start):
visited = [False] * self.num_vertices
self._depth_first_search(start, visited)
def _depth_first_search(self, vertex, visited):
visited[vertex] = True
print(vertex, end=' ')
for i in range(self.num_vertices):
if self.adj_matrix[vertex][i] == 1 and not visited[i]:
self._depth_first_search(i, visited)
def breadth_first_search(self, start):
visited = [False] * self.num_vertices
queue = []
queue.append(start)
visited[start] = True
while queue:
vertex = queue.pop(0)
print(vertex, end=' ')
for i in range(self.num_vertices):
if self.adj_matrix[vertex][i] == 1 and not visited[i]:
queue.append(i)
visited[i] = True
```
这里创建了一个 `Graph` 类,包含了创建邻接矩阵、添加边、删除边、深度优先遍历和广度优先遍历等方法。
在深度优先遍历和广度优先遍历方法中,使用了 `visited` 数组来记录每个顶点是否被访问过。在深度优先遍历中,先将当前顶点标记为已访问,然后递归访问与之相邻的未访问顶点;在广度优先遍历中,先将当前顶点标记为已访问,并将其加入队列中,然后依次访问队列中的顶点,并将与之相邻的未访问顶点加入队列中。
示例:
```python
# 创建一个有 5 个顶点的图
graph = Graph(5)
# 添加边
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
# 深度优先遍历
print("Depth First Search:")
graph.depth_first_search(0)
print()
# 广度优先遍历
print("Breadth First Search:")
graph.breadth_first_search(0)
print()
```
输出结果:
```
Depth First Search:
0 1 2 3 4
Breadth First Search:
0 1 2 3 4
```
阅读全文