티스토리 뷰
const readline = require("readline");
let input = [];
let cabbageField = [];
let result = [];
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.on("line", (line) => input.push(line.trim())).on("close", () => {
const test = parseInt(input[0]);
input.splice(0, 1);
//여러 밭이 나올 수 있어 for문으로 반복
for (let repeat = 0; repeat < test; repeat++) {
let count = 0;
const [x, y, size] = input[0].split(" ").map(Number);
input.splice(0, 1);
cabbageField = Array.from(Array(y), () => Array(x).fill(0));
for (let i = 0; i < size; i++) {
let cabbage = input[i].split(" ").map(Number);
cabbageField[cabbage[1]][cabbage[0]] = 1;
}
//배추밭 만들기
for (let i = 0; i < cabbageField.length; i++) {
for (let j = 0; j < cabbageField[i].length; j++) {
if (dfs(i, j, y, x)) count++;
}
}
result.push(count);
input.splice(0, size);
cabbageField.length = 0;
}
console.log(result.join("\n"));
});
const dfs = (x, y, xLength, yLength) => {
if (x < 0 || x > xLength - 1 || y < 0 || y > yLength - 1) return false;
if (cabbageField[x][y] === 1) {
cabbageField[x][y] = 2;
dfs(x + 1, y, xLength, yLength);
dfs(x - 1, y, xLength, yLength);
dfs(x, y + 1, xLength, yLength);
dfs(x, y - 1, xLength, yLength);
return true;
}
return false;
};
아까 단지번호붙이기와 비슷한 dfs를 이용한 코드이다.
여기서 다른점은 x와 y가 다르기때문에 둘의 길이도 맞춰줘야한다는 점이다.
반응형
'알고리즘 > 백준' 카테고리의 다른 글
백준 7576 [nodejs] 토마토 (0) | 2021.02.04 |
---|---|
백준2178[nodejs] 미로 탐색 (0) | 2021.02.04 |
백준2667[nodejs]단지번호붙이기 (0) | 2021.02.04 |
백준2606[nodejs] 바이러스 (0) | 2021.02.04 |
백준1260[nodejs] DFS와 BFS (0) | 2021.02.03 |
Comments
최근에 올라온 글
최근에 달린 댓글
TAG
- 숫자야구게임
- nodejs
- 정규표현식
- 프로그래머스
- GROUP BY
- smtp error
- 코딩테스트
- 바이러스 dfs
- Express
- JOIN
- JavaScript
- left join
- 카카오2018[1차]
- 로그인
- 534 error
- 백준 7569 node
- 회원가입
- nodemailer error
- 코드테스트
- Level 1
- 백준 7562 node
- SQL
- sort
- AWS
- 토마토3차원
- Replace
- tolowercase
- slice
- 백준
- Split
- Total
- Today
- Yesterday