This commit is contained in:
krahets
2023-03-12 18:46:03 +08:00
parent 209d82a8cc
commit f6b9a75c8f
23 changed files with 406 additions and 359 deletions

View File

@@ -216,14 +216,14 @@ comments: true
class GraphAdjMat:
""" 基于邻接矩阵实现的无向图类 """
# 顶点列表,元素代表“顶点值”,索引代表“顶点索引”
vertices = []
vertices: List[int] = []
# 邻接矩阵,行列索引对应“顶点索引”
adj_mat = []
adj_mat: List[List[int]] = []
def __init__(self, vertices, edges):
def __init__(self, vertices: List[int], edges: List[List[int]]) -> None:
""" 构造方法 """
self.vertices = []
self.adj_mat = []
self.vertices: List[int] = []
self.adj_mat: List[List[int]] = []
# 添加顶点
for val in vertices:
self.add_vertex(val)
@@ -232,23 +232,23 @@ comments: true
for e in edges:
self.add_edge(e[0], e[1])
def size(self):
def size(self) -> int:
""" 获取顶点数量 """
return len(self.vertices)
def add_vertex(self, val):
def add_vertex(self, val: int) -> None:
""" 添加顶点 """
n = self.size()
# 向顶点列表中添加新顶点的值
self.vertices.append(val)
# 在邻接矩阵中添加一行
new_row = [0]*n
new_row = [0] * n
self.adj_mat.append(new_row)
# 在邻接矩阵中添加一列
for row in self.adj_mat:
row.append(0)
def remove_vertex(self, index):
def remove_vertex(self, index: int) -> None:
""" 删除顶点 """
if index >= self.size():
raise IndexError()
@@ -260,7 +260,7 @@ comments: true
for row in self.adj_mat:
row.pop(index)
def add_edge(self, i, j):
def add_edge(self, i: int, j: int) -> None:
""" 添加边 """
# 参数 i, j 对应 vertices 元素索引
# 索引越界与相等处理
@@ -270,7 +270,7 @@ comments: true
self.adj_mat[i][j] = 1
self.adj_mat[j][i] = 1
def remove_edge(self, i, j):
def remove_edge(self, i: int, j: int) -> None:
""" 删除边 """
# 参数 i, j 对应 vertices 元素索引
# 索引越界与相等处理
@@ -279,7 +279,7 @@ comments: true
self.adj_mat[i][j] = 0
self.adj_mat[j][i] = 0
def print(self):
def print(self) -> None:
""" 打印邻接矩阵 """
print("顶点列表 =", self.vertices)
print("邻接矩阵 =")
@@ -965,12 +965,10 @@ comments: true
```python title="graph_adjacency_list.py"
class GraphAdjList:
""" 基于邻接表实现的无向图类 """
# 邻接表key: 顶点value该顶点的所有邻接顶点
adj_list = {}
def __init__(self, edges: List[List[Vertex]]) -> None:
""" 构造方法 """
self.adj_list = {}
# 邻接表key: 顶点value该顶点的所有邻接顶点
self.adj_list: Dict = {}
# 添加所有顶点和边
for edge in edges:
self.add_vertex(edge[0])