带权有向图的邻接表代码实现
时间: 2024-10-06 18:02:59 浏览: 51
带权有向图的邻接表是一种常用的数据结构,它将每个顶点与其对应的边集合关联起来,边的权重通常存储在其对应的节点数据结构中。在Python中,我们可以这样实现:
```python
class Edge:
def __init__(self, src, dest, weight):
self.src = src
self.dest = dest
self.weight = weight
class Vertex:
def __init__(self, id):
self.id = id
self.neighbors = {} # 使用字典存储邻接表,键是邻居顶点ID,值是一个列表存放Edge对象
# 示例图的创建
graph = {}
num_vertices = 5
for i in range(num_vertices):
graph[i] = Vertex(i)
# 添加边及其权重
edges = [(0, 1, 7), (1, 2, 9), (2, 3, 14), (3, 4, 6), (4, 0, 5)]
for edge in edges:
src, dest, weight = edge
if src not in graph or dest not in graph:
raise ValueError("Invalid vertex")
graph[src].neighbors[dest] = [Edge(src, dest, weight)]
# 邻接表操作示例
def get_neighbors(vertex_id):
return graph[vertex_id].neighbors
```
在这个例子中,`get_neighbors`函数可以获取指定顶点的所有邻接边及其权重。
阅读全文