https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에
www.acmicpc.net
📌 작성한 코드
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "Beakjoon/Silver/test.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\n");
const dx = [1, -1, 0, 0];
const dy = [0, 0, 1, -1];
const T = parseInt(input.shift(), 10);
for (let i = 0; i < T; i++) {
const [M, N, K] = input.shift().split(" ").map(Number);
const arr = Array.from({ length: N }, () => new Array(M).fill(0));
for (let j = 0; j < K; j++) {
const [x, y] = input.shift().split(" ").map(Number);
arr[y][x] = 1;
}
const visited = Array.from({ length: N }, () => new Array(M).fill(false));
const dfs = (x, y) => {
const stack = [];
stack.push([x, y]);
while (stack.length) {
const [a, b] = stack.pop();
visited[a][b] = true;
for (let i = 0; i < 4; i++) {
const nx = a + dx[i];
const ny = b + dy[i];
if (nx < 0 || nx >= N || ny < 0 || ny >= M) continue;
if (arr[nx][ny] === 1 && !visited[nx][ny]) {
stack.push([nx, ny]);
}
}
}
};
let count = 0;
for (let i = 0; i < N; i++) {
for (let j = 0; j < M; j++) {
if (!visited[i][j] && arr[i][j] === 1) {
dfs(i, j);
count++;
}
}
}
console.log(count);
}
✅ 성공

'알고리즘 > 백준' 카테고리의 다른 글
| [JavaScript/DFS] 백준 골드 5 : 10026 - 적록색약 (2) | 2024.01.11 |
|---|---|
| [JavaScript/BFS] 백준 골드 5 : 7576 - 토마토 (0) | 2024.01.10 |
| [JavaScript/BFS] 백준 실버 1 : 1926번 - 그림 (0) | 2023.10.10 |
| [JavaScript/DFS] 백준 골드 4 : 2573번 - 빙산 (0) | 2023.09.22 |
| [JavaScript/DFS] 백준 실버 1 : 2468번 - 안전 영역 (0) | 2023.09.21 |