图的两种遍历方法及对应的生成树。自己编写源程序,把图的深度优先遍历、广度优先遍历改为输出深度优先生成树、广度优先生成树。
时间: 2023-07-15 15:14:27 浏览: 170
图的深度与广度优先遍历源程序
以下是深度优先生成树的代码实现:
```python
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def DFS(self, v, visited, parent, dfs_tree):
visited[v] = True
for i in self.graph[v]:
if not visited[i]:
parent[i] = v
dfs_tree[v].append(i)
self.DFS(i, visited, parent, dfs_tree)
def DFS_Tree(self, start):
visited = defaultdict(bool)
parent = defaultdict(int)
dfs_tree = defaultdict(list)
self.DFS(start, visited, parent, dfs_tree)
return dfs_tree
```
以下是广度优先生成树的代码实现:
```python
from collections import defaultdict, deque
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u)
def BFS(self, start, visited, parent, bfs_tree):
queue = deque()
queue.append(start)
visited[start] = True
while queue:
v = queue.popleft()
for i in self.graph[v]:
if not visited[i]:
visited[i] = True
parent[i] = v
bfs_tree[v].append(i)
queue.append(i)
def BFS_Tree(self, start):
visited = defaultdict(bool)
parent = defaultdict(int)
bfs_tree = defaultdict(list)
self.BFS(start, visited, parent, bfs_tree)
return bfs_tree
```
以上两个类中,DFS和BFS方法用于进行深度优先遍历和广度优先遍历,而DFS_Tree和BFS_Tree方法则是对应的深度优先生成树和广度优先生成树。其中,dfs_tree和bfs_tree分别为存储生成树的字典。
阅读全文