-
Notifications
You must be signed in to change notification settings - Fork 0
/
zeroMatrix.js
84 lines (58 loc) · 1.85 KB
/
zeroMatrix.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// take an m*n matrix and if any element is 0, return the matrix with that row and column as 0
// more than 1 zero? yes
// 1 2 3 0 5 6 ---> 0 0 0 0 0 0
// 2 2 2 2 2 ---> 2 2 2 0 2
// 1 2 3 0 5 6 ---> 0 0 0 0 0 0
// 2 2 0 2 2 ---> 0 0 0 0 0
// 0 2 0 0 5 6 ---> 0 0 0 0 0 0
// 0 2 0 2 2 ---> 0 0 0 0 0
// 0 2 3 0 5 6 ---> 0 0 0 0 0 0
// 2 2 2 2 2 ---> 2 2 2 0 2
const rowZeroHasZero = true;
const colZeroHasZero = true;
// 2 2 2 0 2 2 ---> 0 0 0 0 0 0
// 2 2 2 2 2 2 ---> 0 2 2 0 2 2
// 0 2 2 2 2 2 ---> 0 0 0 0 0 0
// 2 2 2 0 2 2 ---> 0 0 0 0 0 0
// 2 2 2 2 2 2 ---> 0 2 2 0 2 2
// 2 2 2 2 2 2 ---> 2 2 2 2 0 2
// 2 2 2 2 2 2 ---> 2 2 2 2 2 2
// 2 2 2 2 2 2 ---> 2 2 2 2 2 2
// 2 2 2 2 0 2 ---> 0 2 2 2 2 2
// 2 2 2 2 2 2 ---> 2 2 2 2 2 2
// O(n) * O(m)
function zeroMatrix(matrix) {
// loop through all elements
// if 0, then that row and column will be zeroed out - take note somewhere somehow
// return array based on collected zero coordinates
// zeros = {rows: [0], cols:[3, 3, 3]}
const zeros = {
rows: [],
cols: []
};
matrix.forEach((a, i) => {
a.forEach((aa, ii) => {
if(aa === 0) {
zeros?.rows.push(i);
zeros?.cols.push(ii);
}
})
})
let generatedMatrix = [];
matrix.forEach((x, i) => {
let c = [];
x.forEach((xx, ii) => {
if(zeros?.rows.includes(i) || zeros?.cols.includes(ii)) {
c.push(0);
} else {
c.push(xx);
}
})
generatedMatrix.push(c);
})
console.log('🪲🪲🪲🪲🪲🪲🪲🪲🪲🪲');
console.log('🪲 generatedMatrix: ', generatedMatrix);
console.log('🪲🪲🪲🪲🪲🪲🪲🪲🪲🪲');
return generatedMatrix;
}
console.log(zeroMatrix([[1, 2, 3, 0, 5, 6], [2, 2, 0, 2, 2]]));