设计一个基于图的邻接矩阵的带权值图的基本操作的演示程序
时间: 2024-02-25 22:53:25 浏览: 23
以下是基于图的邻接矩阵的带权值图的基本操作的演示程序。该程序实现了以下操作:
1. 初始化一个带权值图;
2. 添加边;
3. 删除边;
4. 修改边权值;
5. 打印图的邻接矩阵;
6. 获取指定边的权值。
```python
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
def add_edge(self, u, v, weight):
self.graph[u][v] = weight
self.graph[v][u] = weight
def remove_edge(self, u, v):
self.graph[u][v] = 0
self.graph[v][u] = 0
def modify_edge_weight(self, u, v, weight):
self.graph[u][v] = weight
self.graph[v][u] = weight
def print_graph(self):
for i in range(self.V):
for j in range(self.V):
print(f"{self.graph[i][j]:4}", end="")
print()
def get_edge_weight(self, u, v):
return self.graph[u][v]
g = Graph(4)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)
g.print_graph()
print("Adding edge (1, 2) with weight 8")
g.add_edge(1, 2, 8)
g.print_graph()
print("Removing edge (1, 3)")
g.remove_edge(1, 3)
g.print_graph()
print("Modifying weight of edge (0, 3) to 7")
g.modify_edge_weight(0, 3, 7)
g.print_graph()
print("Weight of edge (2, 3):", g.get_edge_weight(2, 3))
```
输出结果:
```
0 10 6 5
10 0 0 15
6 0 0 4
5 15 4 0
Adding edge (1, 2) with weight 8
0 10 6 5
10 0 8 15
6 8 0 4
5 15 4 0
Removing edge (1, 3)
0 10 6 5
10 0 8 0
6 8 0 4
5 0 4 0
Modifying weight of edge (0, 3) to 7
0 10 6 7
10 0 8 0
6 8 0 4
7 0 4 0
Weight of edge (2, 3): 4
```