문제링크
문제풀이
function solution(maps) {
let m = maps.length;
let n = maps[0].length;
let dx = [1, 0, -1, 0];
let dy = [0, -1, 0, 1];
let ch = Array.from(Array(m), () => Array(n).fill(0));
let dis = Array.from(Array(m), () => Array(n).fill(0));
let queue = [];
queue.push([0, 0]);
dis[0][0] = 1;
ch[0][0] = 1;
while (queue.length) {
let [y, x] = queue.shift();
if (x === n - 1 && y === m - 1) {
break;
}
for (let k = 0; k < 4; k++) {
let x1 = x + dx[k];
let y1 = y + dy[k];
if (
0 <= x1 &&
x1 <= n - 1 &&
0 <= y1 &&
y1 <= m - 1 &&
maps[y1][x1] === 1 &&
ch[y1][x1] === 0
) {
queue.push([y1, x1]);
dis[y1][x1] = dis[y][x] + 1;
ch[y1][x1] = 1;
}
}
}
if (dis[m - 1][n - 1]) {
return dis[m - 1][n - 1];
} else {
return -1;
}
}