一、题目地址
https://leetcode-cn.com/problems/01-matrix/
二、具体代码
var updateMatrix = function(mat) {
let row = mat.length;
let cols = mat[0].length;
// 创建二维数组
let res = Array.from(new Array(mat.length), () => (new Array(mat[0].length)).fill(-1));
let queue = [];
// 初始化res矩阵(为0部分)和为0坐标队列
for(let i=0; i<row; i++) {
for(let j=0; j<cols; j++) {
if(mat[i][j] === 0) {
res[i][j] = 0;
queue.push([i, j].slice(0));
}
}
}
// 当前坐标的四个方向:上右下左
let pos = [[-1, 0], [0, 1], [1, 0], [0, -1]];
let num = 0;
while(queue.length) {
let len = queue.length;
num++;
for(let i=0; i<len; i++) {
let [x, y] = queue.shift();
for(let [xx, yy] of pos) {
let posX = x + xx;
let posY = y + yy;
// 处理边界剪枝,将需填值处(记为-1处)填入距离
if(posX >= 0 && posX < row && posY >= 0 && posY <cols && res[posX][posY] === -1) {
res[posX][posY] = num;
queue.push([posX, posY].slice(0));
}
}
}
}
return res;
};