Skip to content

Commit d6e3890

Browse files
committed
5. Set Matrix Zeroes
1 parent 4755985 commit d6e3890

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

set-matrix-zeroes/sunjae95.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @description
3+
* brainstorming:
4+
* memoization
5+
*
6+
* m: length of matrix
7+
* n: length of matrix[i]
8+
* time complexity: O(m * n)
9+
* space complexity: O(m * n)
10+
*/
11+
var setZeroes = function (matrix) {
12+
const stack = [];
13+
const memo = { row: new Set(), column: new Set() };
14+
15+
const setZero = ({ r, c, isRow, isColumn }) => {
16+
const length = isRow ? matrix.length : matrix[0].length;
17+
18+
for (let i = 0; i < length; i++) {
19+
const row = isRow ? i : r;
20+
const column = isColumn ? i : c;
21+
matrix[row][column] = 0;
22+
}
23+
};
24+
25+
matrix.forEach((row, r) => {
26+
row.forEach((value, c) => {
27+
if (value === 0) stack.push([r, c]);
28+
});
29+
});
30+
31+
while (stack.length) {
32+
const [r, c] = stack.pop();
33+
34+
if (!memo.row.has(r)) {
35+
setZero({ r, c, isColumn: true });
36+
memo.row.add(r);
37+
}
38+
39+
if (!memo.column.has(c)) {
40+
setZero({ r, c, isRow: true });
41+
memo.column.add(c);
42+
}
43+
}
44+
45+
return matrix;
46+
};

0 commit comments

Comments
 (0)