Zero Matrix

Given an m x n matrix, if an element is 0, set its entire row and column to 0 in place.

Example

Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ]
Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]

Solution

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var setZeroes = function(matrix) {
    var row = new Set();
    var column = new Set();
    matrix.forEach( (line, i) => {
        line.forEach( (v, k) => {
            if(v === 0) {
                row.add(i);
                column.add(k);
            }
        })
    } )
    matrix.forEach( (line, i) => {
        line.forEach( (v, k) => {
            if( row.has(i) || column.has(k) ) matrix[i][k] = 0;
        })
    } )
};

Idea

A relatively simple solution is used here. First, two Sets are set up to record the row numbers and column numbers that need to be zeroed. Then the matrix is traversed, and if a value in the matrix is 0, the row number and column number of that value are respectively recorded in the two Sets. Then the entire matrix is traversed again, and if the row number or column number of the value is in the Set, the value in the matrix is set to 0, achieving in-place zeroing.

Daily question

https://github.com/WindrunnerMax/EveryDay

Source

https://leetcode-cn.com/problems/set-matrix-zeroes/