Skip to content

Commit 780e017

Browse files
committed
set matrix zeroes solution
1 parent 5b0bed6 commit 780e017

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

set-matrix-zeroes/hyer0705.ts

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// mark first row, first col - 0ms
2+
/**
3+
Do not return anything, modify matrix in-place instead.
4+
*/
5+
function setZeroes(matrix: number[][]): void {
6+
const m = matrix.length;
7+
const n = matrix[0].length;
8+
9+
let isFirstColZero = false;
10+
let isFirstRowZero = false;
11+
for (let i = 0; i < m; i++) {
12+
for (let j = 0; j < n; j++) {
13+
if (matrix[i][j] === 0) {
14+
if (!isFirstRowZero && i === 0) isFirstRowZero = true;
15+
if (!isFirstColZero && j === 0) isFirstColZero = true;
16+
matrix[i][0] = 0;
17+
matrix[0][j] = 0;
18+
}
19+
}
20+
}
21+
22+
for (let i = 1; i < m; i++) {
23+
for (let j = 1; j < n; j++) {
24+
if (matrix[i][0] === 0 || matrix[0][j] === 0) {
25+
matrix[i][j] = 0;
26+
}
27+
}
28+
}
29+
30+
if (isFirstRowZero) {
31+
for (let j = 0; j < n; j++) {
32+
matrix[0][j] = 0;
33+
}
34+
}
35+
if (isFirstColZero) {
36+
for (let i = 0; i < m; i++) {
37+
matrix[i][0] = 0;
38+
}
39+
}
40+
}
41+
42+
// using set - 4ms
43+
/**
44+
Do not return anything, modify matrix in-place instead.
45+
*/
46+
function setZeroes(matrix: number[][]): void {
47+
const m = matrix.length;
48+
const n = matrix[0].length;
49+
50+
// `${row},${col}`
51+
const coordinates = new Set<string>();
52+
53+
for (let i = 0; i < m; i++) {
54+
for (let j = 0; j < n; j++) {
55+
if (matrix[i][j] === 0) {
56+
coordinates.add(`${i},${j}`);
57+
}
58+
}
59+
}
60+
61+
for (const coordinate of coordinates) {
62+
const [x, y] = coordinate.split(",");
63+
for (let j = 0; j < n; j++) {
64+
matrix[x][j] = 0;
65+
}
66+
for (let i = 0; i < m; i++) {
67+
matrix[i][y] = 0;
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)