|
|
|
@ -13,7 +13,7 @@ from modules import *
|
|
|
|
|
class GraphAdjList:
|
|
|
|
|
"""基于邻接表实现的无向图类"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, edges: list[list[Vertex]]) -> None:
|
|
|
|
|
def __init__(self, edges: list[list[Vertex]]):
|
|
|
|
|
"""构造方法"""
|
|
|
|
|
# 邻接表,key: 顶点,value:该顶点的所有邻接顶点
|
|
|
|
|
self.adj_list = dict[Vertex, Vertex]()
|
|
|
|
@ -27,7 +27,7 @@ class GraphAdjList:
|
|
|
|
|
"""获取顶点数量"""
|
|
|
|
|
return len(self.adj_list)
|
|
|
|
|
|
|
|
|
|
def add_edge(self, vet1: Vertex, vet2: Vertex) -> None:
|
|
|
|
|
def add_edge(self, vet1: Vertex, vet2: Vertex):
|
|
|
|
|
"""添加边"""
|
|
|
|
|
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
|
|
|
|
|
raise ValueError()
|
|
|
|
@ -35,7 +35,7 @@ class GraphAdjList:
|
|
|
|
|
self.adj_list[vet1].append(vet2)
|
|
|
|
|
self.adj_list[vet2].append(vet1)
|
|
|
|
|
|
|
|
|
|
def remove_edge(self, vet1: Vertex, vet2: Vertex) -> None:
|
|
|
|
|
def remove_edge(self, vet1: Vertex, vet2: Vertex):
|
|
|
|
|
"""删除边"""
|
|
|
|
|
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
|
|
|
|
|
raise ValueError()
|
|
|
|
@ -43,14 +43,14 @@ class GraphAdjList:
|
|
|
|
|
self.adj_list[vet1].remove(vet2)
|
|
|
|
|
self.adj_list[vet2].remove(vet1)
|
|
|
|
|
|
|
|
|
|
def add_vertex(self, vet: Vertex) -> None:
|
|
|
|
|
def add_vertex(self, vet: Vertex):
|
|
|
|
|
"""添加顶点"""
|
|
|
|
|
if vet in self.adj_list:
|
|
|
|
|
return
|
|
|
|
|
# 在邻接表中添加一个新链表
|
|
|
|
|
self.adj_list[vet] = []
|
|
|
|
|
|
|
|
|
|
def remove_vertex(self, vet: Vertex) -> None:
|
|
|
|
|
def remove_vertex(self, vet: Vertex):
|
|
|
|
|
"""删除顶点"""
|
|
|
|
|
if vet not in self.adj_list:
|
|
|
|
|
raise ValueError()
|
|
|
|
@ -61,7 +61,7 @@ class GraphAdjList:
|
|
|
|
|
if vet in self.adj_list[vertex]:
|
|
|
|
|
self.adj_list[vertex].remove(vet)
|
|
|
|
|
|
|
|
|
|
def print(self) -> None:
|
|
|
|
|
def print(self):
|
|
|
|
|
"""打印邻接表"""
|
|
|
|
|
print("邻接表 =")
|
|
|
|
|
for vertex in self.adj_list:
|
|
|
|
|