python求有向带权图的dfs、bfs。第一行输入顶点数和边数,第二行输入顶点编号,后面输入起点、终点、权值
时间: 2023-08-18 12:04:06 浏览: 158
有向图.rar_bfs_dfs_dfs有向图栈_joinm3k_深度优先
以下是 Python 实现的有向带权图的 DFS 和 BFS 算法:
```python
from collections import defaultdict, deque
# 定义有向带权图类
class Graph:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
# 添加边
def add_edge(self, u, v, w):
self.graph[u].append((v, w))
# DFS
def dfs(self, start):
visited = [False] * self.V
self._dfs(start, visited)
def _dfs(self, v, visited):
visited[v] = True
print(v, end=" ")
for i in self.graph[v]:
if not visited[i[0]]:
self._dfs(i[0], visited)
# BFS
def bfs(self, start):
visited = [False] * self.V
queue = deque()
visited[start] = True
queue.append(start)
while queue:
s = queue.popleft()
print(s, end=" ")
for i in self.graph[s]:
if not visited[i[0]]:
visited[i[0]] = True
queue.append(i[0])
# 打印图
def print_graph(self):
for i in self.graph:
print(i, " -> ", self.graph[i])
# 测试代码
if __name__ == "__main__":
# 输入顶点数和边数
V, E = map(int, input().split())
# 创建有向带权图对象
g = Graph(V)
# 输入顶点编号、起点、终点、权值
for i in range(E):
u, v, w = map(int, input().split())
g.add_edge(u, v, w)
# 打印图
g.print_graph()
# DFS
start = int(input("请输入 DFS 起点:"))
print("DFS:")
g.dfs(start)
print()
# BFS
start = int(input("请输入 BFS 起点:"))
print("BFS:")
g.bfs(start)
```
输入示例:
```
5 6
1 2 2
1 3 3
2 3 4
2 4 1
3 4 2
4 5 3
```
输出示例:
```
1 -> [(2, 2), (3, 3)]
2 -> [(3, 4), (4, 1)]
3 -> [(4, 2)]
4 -> [(5, 3)]
5 -> []
请输入 DFS 起点:1
DFS:
1 2 3 4 5
请输入 BFS 起点:1
BFS:
1 2 3 4 5
```
阅读全文