1、 编程实现图的遍历图算法(按图的深度优先搜索算法和广度优先搜索算法遍历);
时间: 2023-12-01 17:11:13 浏览: 73
好的,我可以为您编写图的遍历算法。以下是深度优先搜索算法和广度优先搜索算法的实现:
## 深度优先搜索算法
```
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)
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 DFS_traversal(self, v):
visited = [False] * self.V
self.DFS(v, visited)
```
## 广度优先搜索算法
```
from collections import deque
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)
def BFS_traversal(self, v):
visited = [False] * self.V
queue = deque()
queue.append(v)
visited[v] = True
while queue:
v = queue.popleft()
print(v, end=' ')
for i in self.adj[v]:
if not visited[i]:
queue.append(i)
visited[i] = True
```
使用示例:
```
# 创建图对象
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)
g.add_edge(3, 3)
# 深度优先搜索算法遍历
print("深度优先搜索算法遍历(从顶点2开始):")
g.DFS_traversal(2)
# 广度优先搜索算法遍历
print("\n广度优先搜索算法遍历(从顶点2开始):")
g.BFS_traversal(2)
```
输出结果为:
```
深度优先搜索算法遍历(从顶点2开始):
2 0 1 3
广度优先搜索算法遍历(从顶点2开始):
2 0 3 1
```
希望能够帮助到您!
阅读全文