Graph:
class Graph(dict): def __init__(self, vs=[], es=[]): for v in vs: self.add_vertex(v) for e in es: self.add_edge(e) # 必须全部的顶点添加完毕之后,才可以添加新的边进去 def add_vertex(self, v): self[v] = {} def add_edge(self, e): v, w = e self[v][w] = e self[w][v] = e # 无向边以双向连接的方式实现;
vertex:
class Vertex(object): def __init__(self, label=''): self.label = label der __repr__(self): return 'Vertex(%s)' % self.label __str__ = __repr__
edge:
class Edge(tuple): def __new__(cls, e1, e2): return tuple.__new__(cls, (e1, e2)) def __repr(self): return 'Edge(%s, %s)' % (repr(self[0]), repr(self[1])) __str__ = __repr__
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)