Advertisement
hoangreal

Sparse Matrix Multiplication

Oct 19th, 2024 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | Source Code | 0 0
  1. class Solution:
  2.     """
  3.    Multiplies two matrices using sparse matrix representation.
  4.  
  5.    Time Complexity:
  6.    ----------------
  7.    O(m1 * n1 + m2 * n2 + m1 * nonzero_col_mat1 * nonzero_col_mat2)
  8.    - m1, n1: dimensions of mat1
  9.    - m2, n2: dimensions of mat2
  10.    - k: average non-zero elements per row in mat1
  11.  
  12.    Space Complexity:
  13.    -----------------
  14.    O(m1 * n1 + m2 * n2 + m1 * n2)
  15.    - Space for sparse matrices and result matrix.
  16.    """
  17.     def solve(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
  18.  
  19.         sparse_mat1 = self.create_dense_matrix(mat1)
  20.         sparse_mat2 = self.create_dense_matrix(mat2)
  21.         m, n = len(mat1), len(mat2[0])
  22.         result_matrix = [[0] * n for _ in range(m)]
  23.  
  24.         for i in range(m):
  25.             for col_index_mat1, value_mat1 in sparse_mat1[i]:
  26.                 for col_index_mat2, value_mat2 in sparse_mat2[col_index_mat1]:
  27.                     result_matrix[i][col_index_mat2] += value_mat1 * value_mat2
  28.  
  29.         return result_matrix
  30.  
  31.     def create_dense_matrix(self, matrix: List[List[int]]) -> List[List[tuple]]:
  32.         dense_matrix = [[] for _ in range(len(matrix))]
  33.         for row_index, row in enumerate(matrix):
  34.             for col_index, value in enumerate(row):
  35.                 if value:
  36.                     dense_matrix[row_index].append((col_index, value))
  37.         return dense_matrix
Tags: pinterest
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement