-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0073-set-matrix-zeroes.js
More file actions
61 lines (54 loc) · 1.81 KB
/
0073-set-matrix-zeroes.js
File metadata and controls
61 lines (54 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Set Matrix Zeroes
* Time Complexity: O(m*n)
* Space Complexity: O(1)
*/
var setZeroes = function (matrix) {
const matrixRowCount = matrix.length;
const matrixColCount = matrix[0].length;
let shouldZeroFirstRow = false;
let shouldZeroFirstColumn = false;
for (const firstRowItem of matrix[0]) {
if (firstRowItem === 0) {
shouldZeroFirstRow = true;
break;
}
}
let currentColumnCheck = 0;
while (currentColumnCheck < matrixRowCount) {
if (matrix[currentColumnCheck][0] === 0) {
shouldZeroFirstColumn = true;
break;
}
currentColumnCheck++;
}
for (let currentInternalRow = 1; currentInternalRow < matrixRowCount; currentInternalRow++) {
for (let currentInternalCol = 1; currentInternalCol < matrixColCount; currentInternalCol++) {
if (matrix[currentInternalRow][currentInternalCol] === 0) {
matrix[currentInternalRow][0] = 0;
matrix[0][currentInternalCol] = 0;
}
}
}
let targetMatrixRow = 1;
while (targetMatrixRow < matrixRowCount) {
for (let targetMatrixCol = 1; targetMatrixCol < matrixColCount; targetMatrixCol++) {
if (matrix[targetMatrixRow][0] === 0 || matrix[0][targetMatrixCol] === 0) {
matrix[targetMatrixRow][targetMatrixCol] = 0;
}
}
targetMatrixRow++;
}
if (shouldZeroFirstRow) {
for (let fillFirstRowCol = 0; fillFirstRowCol < matrixColCount; fillFirstRowCol++) {
matrix[0][fillFirstRowCol] = 0;
}
}
if (shouldZeroFirstColumn) {
let fillFirstColRow = 0;
while (fillFirstColRow < matrixRowCount) {
matrix[fillFirstColRow][0] = 0;
fillFirstColRow++;
}
}
};