mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-06 22:34:18 +08:00
Update code style for Python
This commit is contained in:
@ -6,18 +6,17 @@ Author: Krahets (krahets@163.com)
|
||||
|
||||
import sys, os.path as osp
|
||||
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
||||
from include import *
|
||||
from modules import *
|
||||
|
||||
|
||||
""" 基于邻接矩阵实现的无向图类 """
|
||||
class GraphAdjMat:
|
||||
""" 基于邻接矩阵实现的无向图类 """
|
||||
# 顶点列表,元素代表“顶点值”,索引代表“顶点索引”
|
||||
vertices = []
|
||||
# 邻接矩阵,行列索引对应“顶点索引”
|
||||
adj_mat = []
|
||||
|
||||
""" 构造方法 """
|
||||
def __init__(self, vertices, edges):
|
||||
""" 构造方法 """
|
||||
self.vertices = []
|
||||
self.adj_mat = []
|
||||
# 添加顶点
|
||||
@ -28,12 +27,12 @@ class GraphAdjMat:
|
||||
for e in edges:
|
||||
self.add_edge(e[0], e[1])
|
||||
|
||||
""" 获取顶点数量 """
|
||||
def size(self):
|
||||
""" 获取顶点数量 """
|
||||
return len(self.vertices)
|
||||
|
||||
""" 添加顶点 """
|
||||
def add_vertex(self, val):
|
||||
""" 添加顶点 """
|
||||
n = self.size()
|
||||
# 向顶点列表中添加新顶点的值
|
||||
self.vertices.append(val)
|
||||
@ -44,9 +43,8 @@ class GraphAdjMat:
|
||||
for row in self.adj_mat:
|
||||
row.append(0)
|
||||
|
||||
|
||||
""" 删除顶点 """
|
||||
def remove_vertex(self, index):
|
||||
""" 删除顶点 """
|
||||
if index >= self.size():
|
||||
raise IndexError()
|
||||
# 在顶点列表中移除索引 index 的顶点
|
||||
@ -57,9 +55,9 @@ class GraphAdjMat:
|
||||
for row in self.adj_mat:
|
||||
row.pop(index)
|
||||
|
||||
""" 添加边 """
|
||||
# 参数 i, j 对应 vertices 元素索引
|
||||
def add_edge(self, i, j):
|
||||
""" 添加边 """
|
||||
# 参数 i, j 对应 vertices 元素索引
|
||||
# 索引越界与相等处理
|
||||
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
|
||||
raise IndexError()
|
||||
@ -67,17 +65,17 @@ class GraphAdjMat:
|
||||
self.adj_mat[i][j] = 1
|
||||
self.adj_mat[j][i] = 1
|
||||
|
||||
""" 删除边 """
|
||||
# 参数 i, j 对应 vertices 元素索引
|
||||
def remove_edge(self, i, j):
|
||||
""" 删除边 """
|
||||
# 参数 i, j 对应 vertices 元素索引
|
||||
# 索引越界与相等处理
|
||||
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
|
||||
raise IndexError()
|
||||
self.adj_mat[i][j] = 0
|
||||
self.adj_mat[j][i] = 0
|
||||
|
||||
""" 打印邻接矩阵 """
|
||||
def print(self):
|
||||
""" 打印邻接矩阵 """
|
||||
print("顶点列表 =", self.vertices)
|
||||
print("邻接矩阵 =")
|
||||
print_matrix(self.adj_mat)
|
||||
|
Reference in New Issue
Block a user