Update graph_adjacency_matrix.py

理解K神这个实现主要是为了演示邻接矩阵的基本原理,但在实际使用中可能会遇到一些限制:在实际应用中,通常使用顶点的值而不是索引来操作图。所以,为了更“公平”地与邻接表方法的对比,进行了改进:
1. 引入 vertex_map:使用字典 vertex_map 来存储顶点值到索引的映射。
2. 基于值的操作:add_vertex, remove_vertex, add_edge, 和 remove_edge 方法现在都使用顶点值而不是索引。这使得图的操作更加直观和用户友好。
3. 动态索引管理:在 remove_vertex 方法中,更新了剩余顶点的索引映射。这确保了在删除顶点后,其他顶点的索引仍然保持正确。
This commit is contained in:
Fuuuuuji 2024-07-26 21:26:57 +08:00 committed by GitHub
parent 89a911583d
commit 95214b144c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -4,113 +4,88 @@ Created Time: 2023-02-23
Author: krahets (krahets@163.com) Author: krahets (krahets@163.com)
""" """
import sys class ImprovedGraphAdjMat:
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from modules import Vertex, print_matrix
class GraphAdjMat:
"""基于邻接矩阵实现的无向图类"""
def __init__(self, vertices: list[int], edges: list[list[int]]): def __init__(self, vertices: list[int], edges: list[list[int]]):
"""构造方法""" self.vertex_map = {} # 用于存储顶点值到索引的映射
# 顶点列表,元素代表“顶点值”,索引代表“顶点索引” self.vertices = []
self.vertices: list[int] = [] self.adj_mat = []
# 邻接矩阵,行列索引对应“顶点索引”
self.adj_mat: list[list[int]] = []
# 添加顶点
for val in vertices: for val in vertices:
self.add_vertex(val) self.add_vertex(val)
# 添加边
# 请注意edges 元素代表顶点索引,即对应 vertices 元素索引
for e in edges: for e in edges:
self.add_edge(e[0], e[1]) self.add_edge(e[0], e[1])
def size(self) -> int:
"""获取顶点数量"""
return len(self.vertices)
def add_vertex(self, val: int): def add_vertex(self, val: int):
"""添加顶点""" if val in self.vertex_map:
n = self.size() return # 如果顶点已存在,直接返回
# 向顶点列表中添加新顶点的值
index = len(self.vertices)
self.vertex_map[val] = index
self.vertices.append(val) self.vertices.append(val)
# 在邻接矩阵中添加一行
new_row = [0] * n # 更新邻接矩阵
self.adj_mat.append(new_row) if self.adj_mat:
# 在邻接矩阵中添加一列 for row in self.adj_mat:
for row in self.adj_mat: row.append(0)
row.append(0) self.adj_mat.append([0] * (index + 1))
def remove_vertex(self, index: int): def remove_vertex(self, val: int):
"""删除顶点""" if val not in self.vertex_map:
if index >= self.size(): return # 如果顶点不存在,直接返回
raise IndexError()
# 在顶点列表中移除索引 index 的顶点 index = self.vertex_map[val]
# 更新顶点列表和映射
self.vertices.pop(index) self.vertices.pop(index)
# 在邻接矩阵中删除索引 index 的行 del self.vertex_map[val]
for v in self.vertices[index:]:
self.vertex_map[v] -= 1
# 更新邻接矩阵
self.adj_mat.pop(index) self.adj_mat.pop(index)
# 在邻接矩阵中删除索引 index 的列
for row in self.adj_mat: for row in self.adj_mat:
row.pop(index) row.pop(index)
def add_edge(self, i: int, j: int): def add_edge(self, v1: int, v2: int):
"""添加边""" if v1 not in self.vertex_map or v2 not in self.vertex_map:
# 参数 i, j 对应 vertices 元素索引 raise ValueError("Vertex not found")
# 索引越界与相等处理
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j: i, j = self.vertex_map[v1], self.vertex_map[v2]
raise IndexError()
# 在无向图中,邻接矩阵关于主对角线对称,即满足 (i, j) == (j, i)
self.adj_mat[i][j] = 1 self.adj_mat[i][j] = 1
self.adj_mat[j][i] = 1 self.adj_mat[j][i] = 1
def remove_edge(self, i: int, j: int): def remove_edge(self, v1: int, v2: int):
"""删除边""" if v1 not in self.vertex_map or v2 not in self.vertex_map:
# 参数 i, j 对应 vertices 元素索引 raise ValueError("Vertex not found")
# 索引越界与相等处理
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j: i, j = self.vertex_map[v1], self.vertex_map[v2]
raise IndexError()
self.adj_mat[i][j] = 0 self.adj_mat[i][j] = 0
self.adj_mat[j][i] = 0 self.adj_mat[j][i] = 0
def print(self): def print(self):
"""打印邻接矩阵"""
print("顶点列表 =", self.vertices) print("顶点列表 =", self.vertices)
print("邻接矩阵 =") print("邻接矩阵 =")
print_matrix(self.adj_mat) for row in self.adj_mat:
print(row)
# 使用示例
graph = ImprovedGraphAdjMat([1, 3, 2, 5, 4], [[1, 3], [1, 5], [3, 2], [2, 5], [2, 4], [5, 4]])
print("\n初始化后,图为")
graph.print()
"""Driver Code""" graph.add_edge(1, 2)
if __name__ == "__main__": print("\n添加边 1-2 后,图为")
# 初始化无向图 graph.print()
# 请注意edges 元素代表顶点索引,即对应 vertices 元素索引
vertices = [1, 3, 2, 5, 4]
edges = [[0, 1], [0, 3], [1, 2], [2, 3], [2, 4], [3, 4]]
graph = GraphAdjMat(vertices, edges)
print("\n初始化后,图为")
graph.print()
# 添加边 graph.remove_edge(1, 3)
# 顶点 1, 2 的索引分别为 0, 2 print("\n删除边 1-3 后,图为")
graph.add_edge(0, 2) graph.print()
print("\n添加边 1-2 后,图为")
graph.print()
# 删除边 graph.add_vertex(6)
# 顶点 1, 3 的索引分别为 0, 1 print("\n添加顶点 6 后,图为")
graph.remove_edge(0, 1) graph.print()
print("\n删除边 1-3 后,图为")
graph.print()
# 添加顶点 graph.remove_vertex(3)
graph.add_vertex(6) print("\n删除顶点 3 后,图为")
print("\n添加顶点 6 后,图为") graph.print()
graph.print()
# 删除顶点
# 顶点 3 的索引为 1
graph.remove_vertex(1)
print("\n删除顶点 3 后,图为")
graph.print()