๐ŸŽฒ๋ฐฑ์ค€ 4963๋ฒˆ ์„ฌ์˜ ๊ฐœ์ˆ˜

Jeongeunยท2023๋…„ 6์›” 10์ผ
0

๋ฐฑ์ค€

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

๋ฐฑ์ค€ 4963๋ฒˆ

๐Ÿงธ DFS, BFS์— ์ ์  ์ต์ˆ™ํ•ด์ ธ๊ฐ€๋Š” ๊ฒƒ ๊ฐ™๋‹ค:)

์ฝ”๋“œ

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

let num = 0;
let result = "";

const DFS = (map, w, h, y, x) => {
  let willCheck = [[y, x]];
  while (willCheck.length) {
    const [pointY, pointX] = willCheck.pop();
    map[pointY][pointX] = 2;
    for (let i = -1; i < 2; i++) {
      for (let j = -1; j < 2; j++) {
        const nextY = pointY + i;
        const nextX = pointX + j;
        if (
          nextY >= 0 &&
          nextY < h &&
          nextX >= 0 &&
          nextX < w &&
          map[nextY][nextX] === 1
        ) {
          willCheck.push([nextY, nextX]);
        }
      }
    }
  }
};

while (true) {
  const [w, h] = input[num].split(" ").map(Number);
  if (w === 0 && h === 0) {
    break;
  }
  let map = [];
  let block = 0;
  for (let i = 0; i < h; i++) {
    num++;
    map.push(input[num].split(" ").map(Number));
  }

  //๊ฐ€๋กœ,์„ธ๋กœ,๋Œ€๊ฐ์„  ์ด๋™ ๊ฐ€๋Šฅ
  for (let i = 0; i < h; i++) {
    for (let j = 0; j < w; j++) {
      if (map[i][j] === 1) {
        DFS(map, w, h, i, j);
        block++;
      }
    }
  }
  result += block + "\n";
  num++;
  
}

console.log(result);

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