修改class arcnode: def __init__(self, adjvex, weight, link=None): self.adjvex = adjvex self.weight = weight self.link = link class vexnode: def __init__(self, data, first_arc=None): self.data = data self.first_arc = first_arc class Graph: def __init__(self): self.vex_list = [] self.vex_num = 0 self.edge_num = 0 # 请在这里填写答案 def addVertex(self, vex_val): new_vertex = vexnode(vex_val) self.vex_list.append(new_vertex) self.vex_num += 1 def addEdge(self, f, t, cost=0): if f not in self.vex_list: nv = self.addVertex(f) # 如果起始顶点不存在,则将其添加到图中 if t not in self.vex_list: nv = self.addVertex(t) # 如果目标顶点不存在,则将其添加到图中 # 无向图添加双向边 self.vex_list[f].addNeighbor(self.vex_list[t], cost) # 将目标顶点及其权重添加到起始顶点的 connectedTo 字典中 self.vex_list[t].addNeighbor(self.vex_list[f], cost) # 有向图只添加一条边 # 请在这里填写答案 def print_graph(self): for i in range(self.vex_num): print(self.vex_list[i].data, end="->") cur = self.vex_list[i].first_arc while cur: print("adj:{},weight:{}".format(cur.adjvex, cur.weight), end="->") cur = cur.link print('None') if __name__ == "__main__": g = Graph() s = input() for vertex in s: g.addVertex(vertex) g.addEdge(0, 1, 11) g.addEdge(0, 2, 55) g.addEdge(2, 3, 88) g.addEdge(0, 3, 33) g.addEdge(1, 2, 44) g.print_graph()
时间: 2024-02-14 10:23:18 浏览: 107
class arcnode:
def __init__(self, adjvex, weight, link=None):
self.adjvex = adjvex
self.weight = weight
self.link = link
class vexnode:
def __init__(self, data, first_arc=None):
self.data = data
self.first_arc = first_arc
class Graph:
def __init__(self):
self.vex_list = []
self.vex_num = 0
self.edge_num = 0
def addVertex(self, vex_val):
new_vertex = vexnode(vex_val)
self.vex_list.append(new_vertex)
self.vex_num += 1
def addEdge(self, f, t, cost=0):
if f not in range(self.vex_num):
raise ValueError("Invalid Starting Vertex")
if t not in range(self.vex_num):
raise ValueError("Invalid Ending Vertex")
new_arc = arcnode(t, cost)
new_arc.link = self.vex_list[f].first_arc
self.vex_list[f].first_arc = new_arc
self.edge_num += 1
def print_graph(self):
for i in range(self.vex_num):
print(self.vex_list[i].data, end="->")
cur = self.vex_list[i].first_arc
while cur:
print("adj:{},weight:{}".format(cur.adjvex, cur.weight), end="->")
cur = cur.link
print('None')
if __name__ == "__main__":
g = Graph()
s = input()
for vertex in s:
g.addVertex(vertex)
g.addEdge(0, 1, 11)
g.addEdge(0, 2, 55)
g.addEdge(2, 3, 88)
g.addEdge(0, 3, 33)
g.addEdge(1, 2, 44)
g.print_graph()
阅读全文