Given two sparse matrices A and B, return the result of AB.
You may assume that A‘s column number is equal to B‘s row number.
Example:
A = [ [ 1, 0, 0], [-1, 0, 3] ] B = [ [ 7, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 1 ] ] | 1 0 0 | | 7 0 0 | | 7 0 0 | AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 | | 0 0 1 |
1 public class Solution { 2 public int[,] Multiply(int[,] A, int[,] B) { 3 int rows = A.GetLength(0), cols = A.GetLength(1), colsB = B.GetLength(1); 4 5 var result = new int[rows, colsB]; 6 7 // since it‘s a sparse matrix, we only want to know rows/cols with a non-zero element 8 var nonZeroRows = new bool[rows]; 9 var nonZeroCols = new bool[colsB]; 10 11 for (int i = 0; i < rows; i++) 12 { 13 for (int j = 0; j < cols; j++) 14 { 15 if (A[i, j] != 0) 16 { 17 nonZeroRows[i] = true; 18 continue; 19 } 20 } 21 } 22 23 // A‘s cols = B‘s rows 24 for (int j = 0; j < colsB; j++) 25 { 26 for (int i = 0; i < cols; i++) 27 { 28 if (B[i, j] != 0) 29 { 30 nonZeroCols[j] = true; 31 continue; 32 } 33 } 34 } 35 36 for (int i = 0; i < rows; i++) 37 { 38 for (int j = 0; j < colsB; j++) 39 { 40 if (nonZeroRows[i] && nonZeroCols[j]) 41 { 42 for (int c = 0; c < cols; c++) 43 { 44 result[i, j] += A[i, c] * B[c, j]; 45 } 46 } 47 } 48 } 49 50 return result; 51 } 52 } 53 54 // brute force, timeout 55 public class Solution1 { 56 public int[,] Multiply(int[,] A, int[,] B) { 57 int rows = A.GetLength(0), cols = A.GetLength(1), colsB = B.GetLength(1); 58 59 var result = new int[rows, colsB]; 60 61 for (int i = 0; i < rows; i++) 62 { 63 for (int j = 0; j < colsB; j++) 64 { 65 for (int c = 0; c < cols; c++) 66 { 67 result[i, j] += A[i, c] * B[c, j]; 68 } 69 } 70 } 71 72 return result; 73 } 74 }