๐ŸŽฒ ๋ฐฑ์ค€ 9328๋ฒˆ ์—ด์‡ 

Jeongeunยท2024๋…„ 2์›” 25์ผ
0

๋ฐฑ์ค€

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

๐Ÿ“ฃ ๋ฌธ์ œ

๐Ÿงธ ์ •๋ง ํž˜๊ฒน๊ฒŒ ํ’€์—ˆ๋‹ค๐Ÿ˜‚
๐ŸŽจ ์ฐธ๊ณ 

์ฝ”๋“œ

const fs = require('fs'); 
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const T = +input.shift();

const dir = [
  [0, 1],
  [0, -1],
  [1, 0],
  [-1, 0],
];

const answer = [];
let i = 0;
for (let t = 0; t < T; t++) {
  const [H, W] = input[i].split(" ").map(Number);
  const map = [];
  map.push(new Array(W + 2).fill("."));
  for (let h = i + 1; h < i + 1 + H; h++) {
    map.push([".", ...input[h].split(""), "."]);
  }
  map.push(new Array(W + 2).fill("."));
  i += H + 1;
  let keys = new Set();
  if (input[i] !== "0") keys = new Set(input[i].split(""));
  const doorPositions = {};
  i++;

  const dfs = () => {
    const stack = [[0, 0]];
    const visited = Array.from(new Array(H + 2), () =>
      new Array(W + 2).fill(false)
    );
    visited[0][0] = true;
    let doc = 0;

    while (stack.length) {
      let [y, x] = stack.pop();
      if (map[y][x].match(new RegExp(/^[A-Z]/))) {
        if (doorPositions[map[y][x].toLowerCase()] === undefined)
          doorPositions[map[y][x].toLowerCase()] = [[y, x]];
        else doorPositions[map[y][x].toLowerCase()].push([y, x]);
        //์—ด์‡  ์—†์Œ
        if (!keys.has(map[y][x].toLowerCase())) {
          continue;
        } else map[y][x] === ".";
      }
      //์—ด์‡  ์ค๊ธฐ
      else if (map[y][x].match(new RegExp(/^[a-z]/))) {
        keys.add(map[y][x]);
        const matching = doorPositions[map[y][x]];
        //๋ฌธ ์—ด์–ด๋†“๊ธฐ
        while (matching !== undefined && matching.length) {
          const [dy, dx] = matching.pop();
          map[dy][dx] = ".";
          stack.push([dy, dx]);
        }
      }
      //๋ฌธ์„œ ํ›”์นจ
      else if (map[y][x] === "$") doc++;

      for (let d = 0; d < 4; d++) {
        const [nextY, nextX] = [y + dir[d][0], x + dir[d][1]];
        if (
          nextX >= W + 2 ||
          nextY >= H + 2 ||
          nextX < 0 ||
          nextY < 0 ||
          map[nextY][nextX] === "*" ||
          visited[nextY][nextX]
        )
          continue;

        visited[nextY][nextX] = true;
        stack.push([nextY, nextX]);
      }
    }

    return doc;
  };

  answer.push(dfs());
}

console.log(answer.join("\n"));

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