How to change all elements of row i and column j in a binary matrix to 0 if cell[i, j] is 0 with Node.js

1 Answer

0 votes
function changeRowColumn(matrix, row, col) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    
    for (let j = 0; j < cols; j++) {
        if (matrix[row][j] != 0) {
            matrix[row][j] = -1;
        }
    }
    
    for (let i = 0; i < rows; i++) {
        if (matrix[i][col] != 0) {
            matrix[i][col] = -1;
        }
    }
}

function changeBinaryMatrix(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;
    
    if (rows == 0 || cols == 0) {
        return;
    }
    
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (matrix[i][j] == 0) {
                changeRowColumn(matrix, i, j);
            }
        }
    }
    
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (matrix[i][j] == -1) {
                matrix[i][j] = 0;
            }
        }
    }
}
   
function printMatrix(matrix) {
    const rows = matrix.length;
    const cols = matrix[0].length;

    for (let i = 0; i < rows; i++) {
        let s = "";
        for (let j = 0; j < cols; j++) {
            s += matrix[i][j] + " ";
        }
        console.log(s);
    }
}
        
const matrix = [[1, 1, 0, 1, 1, 1], 
                [1, 1, 1, 1, 1, 1], 
                [1, 1, 0, 1, 1, 1], 
                [1, 1, 1, 1, 1, 1], 
                [1, 0, 1, 1, 1, 1]];
     
changeBinaryMatrix(matrix);

printMatrix(matrix);

 
 
 
 
 
/*
run:
    
0 0 0 0 0 0 
1 0 0 1 1 1 
0 0 0 0 0 0 
1 0 0 1 1 1 
0 0 0 0 0 0  
        
*/

 

 



answered Jan 22, 2024 by avibootz
...