๐ŸŽฒ ๋ฐฑ์ค€ 2206๋ฒˆ ๋ฒฝ ๋ถ€์ˆ˜๊ณ  ์ด๋™ํ•˜๊ธฐ

Jeongeunยท2023๋…„ 9์›” 5์ผ
0

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
118/187

๋ฐฑ์ค€ 2206๋ฒˆ

๐Ÿ’ก ์ด๋™ ๊ฐ€๋Šฅ ๊ตฌ์—ญ์— ์™”์„ ๋•Œ, ๋ฒฝ์„ ๋šซ๊ณ  ์™”๋Š”์ง€ ๋ฒฝ์„ ์•ˆ ๋šซ๊ณ  ์™”๋Š”๋ฐ ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ์–ด 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);

0๊ฐœ์˜ ๋Œ“๊ธ€