Journal Archive

/**
 * @param {number[][]} mat
 * @return {number[][]}
 **/
var updateMatrix = function(mat) {
    
    const maxDistance = mat.length - 1 + mat[0].length - 1;
    // dynamic programming method
    // top to bottom, comparing above and left cells
    for (let i = 0; i < mat.length; i ++) {
        for (let j = 0; j < mat[0].length; j++) {
            if (mat[i][j] !== 0){
                let cellAbove = i - 1 < 0 ? maxDistance: mat[i - 1][j];
                let cellLeft = j - 1 < 0 ? maxDistance: mat[i][j - 1];
                // update cell
                mat[i][j] = Math.min(cellAbove, cellLeft) + 1; 
            }
        }
    }
    
    // bottom to top, comparing right and below cells
    for (let i = mat.length - 1; i >= 0; i--) {
        for (let j = mat[0].length - 1; j >= 0; j--) {
            if (mat[i][j] !== 0) {
                let cellBelow = i + 1 >= mat.length ? maxDistance : mat[i + 1][j];
                let cellRight = j + 1 >= mat[0].length ? maxDistance : mat[i][j + 1];
                // update cell and compare with old value
                mat[i][j] = Math.min(cellBelow + 1, cellRight + 1, mat[i][j]);
            }
        }
    }
    return mat;
};

Day 19: Solving one of LeetCode problems

542. 01 Matrix Difficulty - Medium

Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.

The distance between two adjacent cells is 1.

 

Example 1:

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

Example 2:

Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]