Skip to content

Commit d7c9611

Browse files
committed
update doc/cheatsheet/matrix.md
1 parent 1d170af commit d7c9611

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

doc/cheatsheet/matrix.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
- Spiral Matrix I
1515
- LC 54
1616
- LC 59
17+
- Sparse matrix product
18+
- LC 311
1719

1820
- Algorithm
1921
- [fucking algorithm : 二维数组的花式遍历技巧](https://labuladong.github.io/algo/2/20/26/)
@@ -401,4 +403,67 @@ class Solution(object):
401403
res = []
402404
dfs(matrix, target, 0, 0)
403405
return True in res
406+
```
407+
408+
### 2-7) Sparse Matrix Multiplication
409+
410+
```java
411+
// java
412+
// LC 311
413+
// V0
414+
// IDEA : ARRAY OP (fix by gpt)
415+
/**
416+
* Why there is 3 loop ?
417+
*
418+
* -> Matrix Multiplication: Ci,j = Sigma(Aik * Bkj)
419+
*
420+
* -> so we have 3 layer loop as below:
421+
* - i : Iterates over the rows of A (outer loop).
422+
* - j : Iterates over the columns of B (second loop).
423+
* - k : Iterates over the “shared dimension” (columns of A or rows of B ) to compute the dot product (inner loop).
424+
*
425+
*
426+
* ->
427+
*
428+
* The Role of the Loops
429+
* 1. Outer loop ( i ): Iterates over the rows of mat1 to calculate each row of the result matrix.
430+
* 2. Middle loop ( j ): Iterates over the columns of mat2 to compute each element in a row of the result matrix.
431+
* 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.
432+
*
433+
*
434+
* -> Why the Inner Loop ( k ) Exists ?
435+
*
436+
* -> The inner loop is necessary
437+
* because each element of the result matrix
438+
* is computed as the dot product of a
439+
* row from mat1 and a column from mat2.
440+
* Without this loop, the computation of the dot product would be incomplete.
441+
*/
442+
public static int[][] multiply(int[][] mat1, int[][] mat2) {
443+
// Edge case: Single element matrices
444+
if (mat1.length == 1 && mat1[0].length == 1 && mat2.length == 1 && mat2[0].length == 1) {
445+
return new int[][]{{mat1[0][0] * mat2[0][0]}};
446+
}
447+
448+
int l_1 = mat1.length; // Number of rows in mat1
449+
int w_1 = mat1[0].length; // Number of columns in mat1 (and rows in mat2)
450+
451+
int w_2 = mat2[0].length; // Number of columns in mat2
452+
453+
// Initialize the result matrix
454+
int[][] res = new int[l_1][w_2];
455+
456+
// Perform matrix multiplication
457+
for (int i = 0; i < l_1; i++) {
458+
for (int j = 0; j < w_2; j++) {
459+
int sum = 0; // Sum for res[i][j]
460+
for (int k = 0; k < w_1; k++) {
461+
sum += mat1[i][k] * mat2[k][j];
462+
}
463+
res[i][j] = sum;
464+
}
465+
}
466+
467+
return res;
468+
}
404469
```

0 commit comments

Comments
 (0)