๐ก ์ด๋ ๊ฐ๋ฅ ๊ตฌ์ญ์ ์์ ๋, ๋ฒฝ์ ๋ซ๊ณ ์๋์ง ๋ฒฝ์ ์ ๋ซ๊ณ ์๋๋ฐ ๋ ๊ฐ์ง ๊ฒฝ์ฐ๊ฐ ์์ ์ ์์ด checked๋ฐฐ์ด์ 3์ฐจ์์ผ๋ก ๋ง๋ค์ด์ฃผ์๋ค.
๐ N,M์ด 1์ผ ๋ ๊ฒฝ์ฐ๋ ์ฒ๋ฆฌํด์ฃผ์ด์ผํ๋ค.
๐ shift()๋ฅผ ํด์ฃผ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ์ฌ index๋ฅผ ์ฆ๊ฐ์ํค๋ ๋ฐฉ๋ฒ์ ์ฌ์ฉํ๋ค.
๐จ ๋ฐ๋ก๋ชจ์
์ฝ๋
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const [N, M] = input.shift().split(" ").map(Number);
const map = input.map((el) => el.split("").map(Number));
const dir = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
let answer = -1;
const checked = Array.from(new Array(N), () =>
Array.from(new Array(M), () => new Array(2).fill(false))
);
const bfs = () => {
const queue = [[0, 0, false, 1]];
checked[0][0][0] = true;
checked[0][0][1] = true;
let index = 0;
if (N === 1 && M === 1) {
answer = 1;
return;
}
while (queue.length > index) {
const [locY, locX, crush, distance] = queue[index];
for (let d = 0; d < 4; d++) {
const nextY = locY + dir[d][0];
const nextX = locX + dir[d][1];
if (
nextX < 0 ||
nextY < 0 ||
nextX >= M ||
nextY >= N ||
map[nextY][nextX] === -1
)
continue;
if (nextY === N - 1 && nextX === M - 1) {
answer = distance + 1;
return;
}
if (map[nextY][nextX] === 0) {
//์ด๋ ๊ฐ๋ฅ ๊ตฌ์ญ
//๋ฒฝ ๋ซ๊ณ ์ด
if (crush && !checked[nextY][nextX][0]) {
queue.push([nextY, nextX, crush, distance + 1]);
checked[nextY][nextX][0] = true;
}
//๋ฒฝ ์ ๋ซ๊ณ ์ด
if (!crush && !checked[nextY][nextX][1]) {
queue.push([nextY, nextX, crush, distance + 1]);
checked[nextY][nextX][1] = true;
}
} else {
//๋ฒฝ
//๋ฒฝ ๋ซ์ ์ ์๋ค๋ฉด
if (!crush) {
queue.push([nextY, nextX, true, distance + 1]);
map[nextY][nextX] = -1;
}
}
}
index++;
}
};
bfs();
console.log(answer);