class Node: def __init__(self, row, col, value): self.row = row # 行索引 self.col = col # 列索引 self.value = value # 节点值 self.right = None # 右侧节点 self.down = None # 下方节点 class SparseMatrix: def __init__(self, matrix): self.matrix = matrix # 原始矩阵 self.row_heads = [None] * len(matrix) # 每行的头节点列表 self.col_heads = [None] * len(matrix[0]) # 每列的头节点列表 self.build_sparse_matrix() # 构建稀疏矩阵 def build_sparse_matrix(self): for i in range(len(self.matrix)): for j in range(len(self.matrix[0])): if self.matrix[i][j]!= 0: new_node = Node(i, j, self.matrix[i][j]) # 创建新节点 if self.row_heads[i] is None: self.row_heads[i] = new_node # 设置行头节点 else: current = self.row_heads[i] while current.right is not None and current.right.col < j: current = current.right # 寻找插入位置 new_node.right = current.right current.right = new_node # 插入新节点 if self.col_heads[j] is None: self.col_heads[j] = new_node # 设置列头节点 else: current = self.col_heads[j] while current.down is not None and current.down.row < i: current = current.down # 寻找插入位置 new_node.down = current.down current.down = new_node # 插入新节点 def add(self, other): if len(self.matrix)!= len(other.matrix) or len(self.matrix[0])!= len(other.matrix[0]): raise ValueError('矩阵的维度不匹配,无法相加!') result = [[0] * len(self.matrix[0]) for _ in range(len(self.matrix))] for i in range(len(self.matrix)): self_row_node = self.row_heads[i] other_row_node = other.row_heads[i] while self_row_node is not None or other_row_node is not None: if self_row_node is not None and other_row_node is not None: if self_row_node.col == other_row_node.col: result[i][self_row_node.col] = self_row_node.value + other_row_node.value self_row_node = self_row_node.right other_row_node = other_row_node.right elif self_row_node.col < other_row_node.col: result[i][self_row_node.col] = self_row_node.value self_row_node = self_row_node.right else: result[i][other_row_node.col] = other_row_node.value other_row_node = other_row_node.right elif self_row_node is not None: result[i][self_row_node.col] = self_row_node.value self_row_node = self_row_node.right elif other_row_node is not None: result[i][other_row_node.col] = other_row_node.value other_row_node = other_row_node.right return result matrix1 = [ [0, 0, 3], [4, 0, 0], [0, 2, 0] ] matrix2 = [ [1, 0, 0], [0, 5, 0], [0, 0, 6] ] sparse_matria1 = SparseMatrix(matrix1) sparse_matria2 = SparseMatrix(matrix2) result=sparse_matria1.add(sparse_matria2) print(result)
python数据结构——相加运算(完整)
于 2024-05-22 11:40:08 首次发布