图的构造与遍历代码
时间: 2024-02-19 17:02:30 浏览: 64
树的构造和遍历.txt
以下是一个基于邻接矩阵表示图的构造和遍历的代码示例:
```python
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.adj_matrix = [[0 for i in range(vertices)] for j in range(vertices)]
def add_edge(self, u, v):
self.adj_matrix[u][v] = 1
self.adj_matrix[v][u] = 1
def remove_edge(self, u, v):
self.adj_matrix[u][v] = 0
self.adj_matrix[v][u] = 0
def dfs(self, start_vertex):
visited = [False for i in range(self.vertices)]
self._dfs(start_vertex, visited)
def _dfs(self, vertex, visited):
visited[vertex] = True
print(vertex, end=' ')
for i in range(self.vertices):
if self.adj_matrix[vertex][i] and not visited[i]:
self._dfs(i, visited)
def bfs(self, start_vertex):
visited = [False for i in range(self.vertices)]
queue = []
queue.append(start_vertex)
visited[start_vertex] = True
while queue:
vertex = queue.pop(0)
print(vertex, end=' ')
for i in range(self.vertices):
if self.adj_matrix[vertex][i] and not visited[i]:
queue.append(i)
visited[i] = True
```
在上面的代码中,我们定义了一个 `Graph` 类来表示图,使用邻接矩阵来存储图的关系。`add_edge()` 和 `remove_edge()` 方法可以用来添加或删除边。`dfs()` 和 `bfs()` 方法分别实现深度优先遍历和广度优先遍历。其中,`_dfs()` 是一个辅助方法,用来递归地遍历图。
使用示例:
```python
g = Graph(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
print("DFS traversal:")
g.dfs(0)
print("\nBFS traversal:")
g.bfs(0)
```
输出结果:
```
DFS traversal:
0 1 2 3
BFS traversal:
0 1 2 3
```
阅读全文