Open jtkaufman737 opened 5 years ago
This is perhaps my least favorite solution to any of the CTCI problems I've had thus far but I wanted to move on so here we are.
function zeroMatrix(m) {
let newArr = [], indexes = [];
// copy original because I'm having stupid mutability issues
for(let i=0; i < m.length; i++) {
newArr.push([]);
for(let j=0; j < m[i].length; j++) {
newArr[i][j] = m[i][j];
}
}
for(let i=0; i < m.length; i++) {
if(m[i].includes(0)) { // head off unnecessary looping
for(let j=0; j < m[i].length; j++) { // items in row
newArr[i][j] = 0; // set each to 0
m[i][j] === 0 ? indexes.push(j) : '';
}
}
}
for(let i=0; i < m.length; i++) {
for(let j=0; j < indexes.length; j++) {
let key = indexes[j];
newArr[i][key] = 0;
}
}
console.log("Old array vs new array:");
console.log(m);
console.log(newArr);
}
zeroMatrix([[1,1,1],[0,2,0],[3,4,5]]) // end should be [0,1,0][0,0,0][0,4,0]
1.8 Zero Matrix
Write an algorithm such that if an element in an MXN matrix is 0, its entire row and column are set to zero