深度优先遍历无向加权图
时间: 2023-12-25 14:28:22 浏览: 91
图的深度优先遍历
以下是深度优先遍历无向加权图的Python实现:
```python
# 定义一个无向加权图的类
class Graph:
def __init__(self):
self.graph = {}
# 添加边
def add_edge(self, u, v, w):
if u not in self.graph:
self.graph[u] = {}
self.graph[u][v] = w
if v not in self.graph:
self.graph[v] = {}
self.graph[v][u] = w
# 深度优先遍历
def dfs(self, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
for neighbor in self.graph[start]:
if neighbor not in visited:
self.dfs(neighbor, visited)
# 创建一个无向加权图
g = Graph()
g.add_edge('A', 'B', 1)
g.add_edge('A', 'C', 2)
g.add_edge('B', 'D', 3)
g.add_edge('B', 'E', 4)
g.add_edge('C', 'F', 5)
g.add_edge('D', 'G', 6)
g.add_edge('E', 'G', 7)
g.add_edge('F', 'H', 8)
# 从顶点A开始进行深度优先遍历
g.dfs('A')
```
输出结果为:A B D G E C F H
阅读全文