class Graph: def __init__(self): self.vertices = {} self.numVertices = 0 # 初始图 顶点0 def addVertex(self, key): # add顶点 self.numVertices = self.numVertices + 1 newVertex = Vertex(key) self.vertices[key] = newVertex # 顶点对应属性 return newVertex def getVertex(self, key): if key in self.vertices: return self.vertices[key] else: return None def __contains__(self, key): # check判断是否存在 return key in self.vertices def addEdge(self, f, t, cost): # 添加边 if f not in self.vertices: nv = self.addVertex(f) # 顶点未在图的顶点集先加入 if t not in self.vertices: nv = self.addVertex(t) self.vertices[f].addNeighbor(self.vertices[t], cost) # 添加邻接点 def addNeighbor(self, nbr, weight): # 加上可至顶点,路径权重 self.connectedTo[nbr] = weight上述代码如何给Graph添加边
时间: 2024-02-14 14:05:01 浏览: 99
GPAC.rar_graph image_graph 分割_image segmentation_site:www.pudn.c
可以使用Graph类中的addEdge方法来添加边。该方法接受两个顶点的键以及边的权重作为参数,会在图中添加这两个顶点,并在第一个顶点的邻接点列表中添加指向第二个顶点的邻接点以及对应的权重。例如,如果要添加从顶点A到顶点B的权重为3的边,可以这样调用方法:
```
graph = Graph()
graph.addEdge('A', 'B', 3)
```
阅读全文