无向带权图删边的代码
时间: 2024-05-06 11:11:35 浏览: 52
对于无向带权图的删除边操作,可以通过遍历边集合,找到需要删除的边并移除它。下面是一个示例代码:
```python
class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.adj_list = [[] for _ in range(num_vertices)]
self.edges = []
def add_edge(self, u, v, weight):
self.adj_list[u].append((v, weight))
self.adj_list[v].append((u, weight))
self.edges.append((u, v, weight))
def remove_edge(self, u, v):
for i, (x, y, _) in enumerate(self.edges):
if (u, v) == (x, y) or (v, u) == (x, y):
self.adj_list[u] = [edge for edge in self.adj_list[u] if edge[0] != v]
self.adj_list[v] = [edge for edge in self.adj_list[v] if edge[0] != u]
del self.edges[i]
break
# 创建一个无向带权图
g = Graph(5)
g.add_edge(0, 1, 2)
g.add_edge(0, 3, 5)
g.add_edge(1, 2, 3)
g.add_edge(1, 4, 1)
g.add_edge(2, 3, 4)
# 删除边(1, 4)
g.remove_edge(1, 4)
```
阅读全文