๐ŸŽฒ ๋ฐฑ์ค€ 5427๋ฒˆ ๋ถˆ

Jeongeunยท2023๋…„ 8์›” 16์ผ
0

๋ฐฑ์ค€

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

๋ฐฑ์ค€ 5427๋ฒˆ

๐Ÿ’Š ์ฒ˜์Œ์— ์‚ฌ๋žŒ์ด ์ด๋™ํ•˜๊ณ  ๋ถˆ์ด ๋ฒˆ์งˆ ์ˆ˜ ์žˆ์œผ๋‹ˆ๊นŒ ํ์— ์‚ฌ๋žŒ ์œ„์น˜๋ฅผ ๋จผ์ €๋„ฃ์–ด์•ผ ๋œ๋‹ค ์ƒ๊ฐํ•˜๊ณ  ํ’€์—ˆ๋‹ค. ํ•˜๋‹ค๊ฐ€ ์–ด๋ผ ์ด๋Ÿฌ๋ฉด ๋ถˆ์ด ๋ฒˆ์ง€๋Š” ๊ณณ์œผ๋กœ ๊ฐˆ ์ˆ˜๊ฐ€ ์žˆ๊ฒ ๋„ค ํ•˜๊ณ  ์ˆ˜์ •ํ•ด์ฃผ์—ˆ๋‹ค.
๐Ÿ’Š ๊ทธ๋ฆฌ๊ณ  ์ดˆ๊ธฐ์— ํ์— ๋„ฃ์–ด์ฃผ๋Š” ์ž‘์—…์„ ํ•  ๋•Œ, if๋ฌธ์ธ ๋ถˆ์ด๋ผ๋ฉด~์„ ์‚ฌ๋žŒ์ด๋ผ๋ฉด~๋ณด๋‹ค ๋จผ์ € ํ•ด์คฌ๋‹ค๊ณ  ๋ถˆ ๋จผ์ € ๋“ค์–ด๊ฐ”๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋‹คใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ ๋ฐ˜๋ก€๋ฅผ ํ•ด๋ณด๋‹ค๊ฐ€ ๊นจ๋‹ฌ์•˜๋‹ค.
๐Ÿ’ก ์ดˆ๊ธฐ์— ํ์— ๋„ฃ๋Š” ์ž‘์—…์—์„œ ๋ถˆ์ด ๋จผ์ €๋“ค์–ด๊ฐ€๋Š” ๊ฒƒ์„ ์•Œ๋ฉด ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ๊ฐ™๋‹ค. bfsํƒ์ƒ‰์—์„œ๋Š” ๋ถˆ์ผ ๊ฒฝ์šฐ์™€ ์‚ฌ๋žŒ์ผ ๊ฒฝ์šฐ๋ฅผ ๋‚˜๋ˆ„์–ด ํ‰์†Œ ํ•˜๋˜๋Œ€๋กœ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

const fs = require('fs'); 
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const N = +input.shift();
const dir = [
  [0, 1],
  [0, -1],
  [-1, 0],
  [1, 0],
];

let index = 0;
for (let n = 0; n < N; n++) {
  const [w, h] = input[index].split(" ").map(Number);
  let arr = [];
  for (let i = 1; i <= h; i++) {
    arr.push(input[index + i].split(""));
  }
  const queue = [];

  let position;
  for (let i = 0; i < h; i++) {
    for (let j = 0; j < w; j++) {
      if (arr[i][j] === "*") {
        queue.push(["*", i, j, 0]);
      }
      if (arr[i][j] === "@") {
        position = ["@", i, j, 0];
        arr[i][j] = "x";
      }
    }
  }
  queue.push(position);
  let impossible = true;
  let flag = 0;
  while (flag < queue.length) {
    const [type, pY, pX, time] = queue[flag];
    if (
      type === "@" &&
      (pX === 0 || pY === 0 || pX === w - 1 || pY === h - 1)
    ) {
      console.log(time + 1);
      impossible = false;
      break;
    }

    for (let d = 0; d < 4; d++) {
      const nY = pY + dir[d][0];
      const nX = pX + dir[d][1];
      if (nY >= 0 && nY < h && nX >= 0 && nX < w) {
        if (type === "@") {
          if (arr[nY][nX] === ".") {
            queue.push(["@", nY, nX, time + 1]);
            arr[nY][nX] = "x";
          }
        } else {
          if (arr[nY][nX] !== "#" && arr[nY][nX] !== "*") {
            queue.push(["*", nY, nX, time + 1]);
            arr[nY][nX] = "*";
          }
        }
      }
    }
    flag++;
 
  }
  if (impossible) console.log("IMPOSSIBLE");

  index += h + 1;
}

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