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 13:05:01 浏览: 101
可以使用Graph类中的addEdge方法来添加边。该方法接受两个顶点的键以及边的权重作为参数,会在图中添加这两个顶点,并在第一个顶点的邻接点列表中添加指向第二个顶点的邻接点以及对应的权重。例如,如果要添加从顶点A到顶点B的权重为3的边,可以这样调用方法:
```
graph = Graph()
graph.addEdge('A', 'B', 3)
```
相关问题
按照如下定义给G=Graph()添加边举例子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) # 添加邻接点
好的,假设我们要给这个图添加一条从顶点0到顶点1的边,边权为2,代码如下:
```
G = Graph()
G.addVertex(0)
G.addVertex(1)
G.addEdge(0, 1, 2)
```
这样就在图中添加了一条从顶点0到顶点1的边,边权为2。
class Node: def __init__(self, num, name, intro): self.num = num self.name = name self.intro = intro self.visited = False class Edge: def __init__(self, fr, to, weight): self.fr = fr self.to = to self.weight = weight class Graph: def __init__(self): self.nodes = [] self.edges = {} def add_node(self, node): self.nodes.append(node) self.edges[node] = [] def add_edge(self, edge): self.edges[edge.fr].append(edge) self.edges[edge.to].append(Edge(edge.to, edge.fr, edge.weight))graph = Graph() with open('data.txt', 'r', encoding='utf-8') as f: for line in f.readlines(): items = line.strip().split(',') num = int(items[0]) name = items[1] intro = items[2] node = Node(num, name, intro) graph.add_node(node) for i in range(3, len(items), 2): neighbor = int(items[i]) weight = int(items[i+1]) edge = Edge(node, graph.nodes[neighbor-1], weight) graph.add_edge(edge) data.txt里怎么写
data.txt 的格式应该是每一行代表一个节点和它的邻居节点以及边的权重,具体格式如下:
节点编号,节点名称,节点介绍,邻居节点1,边的权重1,邻居节点2,边的权重2,...
例如:
1,Node1,This is Node1,2,10,3,15,4,20
2,Node2,This is Node2,1,10,3,5
3,Node3,This is Node3,1,15,2,5,4,8
4,Node4,This is Node4,1,20,3,8
阅读全文