diff --git a/doc/cheatsheet/matrix.md b/doc/cheatsheet/matrix.md index 7dbf9025..e69f04dc 100644 --- a/doc/cheatsheet/matrix.md +++ b/doc/cheatsheet/matrix.md @@ -14,6 +14,8 @@ - Spiral Matrix I - LC 54 - LC 59 + - Sparse matrix product + - LC 311 - Algorithm - [fucking algorithm : 二维数组的花式遍历技巧](https://labuladong.github.io/algo/2/20/26/) @@ -401,4 +403,67 @@ class Solution(object): res = [] dfs(matrix, target, 0, 0) return True in res +``` + +### 2-7) Sparse Matrix Multiplication + +```java +// java +// LC 311 +// V0 +// IDEA : ARRAY OP (fix by gpt) +/** +* Why there is 3 loop ? +* +* -> Matrix Multiplication: Ci,j = Sigma(Aik * Bkj) +* +* -> so we have 3 layer loop as below: +* - i : Iterates over the rows of A (outer loop). +* - j : Iterates over the columns of B (second loop). +* - k : Iterates over the “shared dimension” (columns of A or rows of B ) to compute the dot product (inner loop). +* +* +* -> +* +* The Role of the Loops +* 1. Outer loop ( i ): Iterates over the rows of mat1 to calculate each row of the result matrix. +* 2. Middle loop ( j ): Iterates over the columns of mat2 to compute each element in a row of the result matrix. +* 3. Inner loop ( k ): Iterates over the “shared dimension” to compute the dot product of the i^{th} row of mat1 and the j^{th} column of mat2. +* +* +* -> Why the Inner Loop ( k ) Exists ? +* +* -> The inner loop is necessary +* because each element of the result matrix +* is computed as the dot product of a +* row from mat1 and a column from mat2. +* Without this loop, the computation of the dot product would be incomplete. +*/ +public static int[][] multiply(int[][] mat1, int[][] mat2) { + // Edge case: Single element matrices + if (mat1.length == 1 && mat1[0].length == 1 && mat2.length == 1 && mat2[0].length == 1) { + return new int[][]{{mat1[0][0] * mat2[0][0]}}; + } + + int l_1 = mat1.length; // Number of rows in mat1 + int w_1 = mat1[0].length; // Number of columns in mat1 (and rows in mat2) + + int w_2 = mat2[0].length; // Number of columns in mat2 + + // Initialize the result matrix + int[][] res = new int[l_1][w_2]; + + // Perform matrix multiplication + for (int i = 0; i < l_1; i++) { + for (int j = 0; j < w_2; j++) { + int sum = 0; // Sum for res[i][j] + for (int k = 0; k < w_1; k++) { + sum += mat1[i][k] * mat2[k][j]; + } + res[i][j] = sum; + } + } + + return res; +} ``` \ No newline at end of file