말랑말랑 LAB

leetcode#73 Set Matrix Zeroes 본문

JavaScript/Algorithm

leetcode#73 Set Matrix Zeroes

쭈02 2021. 8. 21. 13:51

Question

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.

You must do it in place.

 

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[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]]

 

Constraints:

  • m == matrix.length
  • n == matrix[0].length
  • 1 <= m, n <= 200
  • -231 <= matrix[i][j] <= 231 - 1

 

Follow up:

  • A straightforward solution using O(mn) space is probably a bad idea.
  • A simple improvement uses O(m + n) space, but still not the best solution.
  • Could you devise a constant space solution?

 

solution

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var setZeroes = function(matrix) {
    var result = matrix.map(v => v.slice());
    var row = matrix.length;
    var col = matrix[0].length;
    
    var [targetRow, targetCol] = [0, 0];
    
    for(var i=0; i<row; i++) {
        for(var j=0; j<col; j++) {
            if (matrix[i][j] === 0) {
                targetRow = i;
                targetCol = j;
                
                var tRow = targetRow + 1;
                while(tRow >= 0 && tRow < row) {
                    if (result[tRow][targetCol] !== 0) {
                        result[tRow][targetCol] = 0;
                    }
                    tRow++;
                }
                
                var tRow = targetRow - 1;
                while(tRow >= 0 && tRow < row) {
                    if (result[tRow][targetCol] !== 0) {
                        result[tRow][targetCol] = 0;
                    }
                    tRow--;
                }
            
                var tCol = targetCol + 1;
                while(tCol >= 0 && tCol < col) {
                    if (result[targetRow][tCol] !== 0) {
                        result[targetRow][tCol] = 0;
                    }
                    tCol++;
                }
                
                var tCol = targetCol - 1;
                while(tCol >= 0 && tCol < col) {
                    if (result[targetRow][tCol] !== 0) {
                        result[targetRow][tCol] = 0;
                    }
                    tCol--;
                }
            }
        }
    }
    
    matrix = result;
};
Comments