๐งธ 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);