728x90
문제
https://www.acmicpc.net/problem/11403
문제 해석
이 문제는 그래프 이론과 비슷한 방법으로 풀면 된다.
다만, 정점 i에서 j로 가는 간선임으로 graph 추가 시 양 방향 추가가 아닌 단 방향으로 추가해 주면 된다.
풀이
const filePath = process.platform === "linux" ? "dev/stdin" : "../test.txt";
const input = require("fs").readFileSync(filePath).toString().trim().split("\n");
function solution(input) {
const [N, M] = input.shift().split(" ").map(Number);
const lines = input.map((v) => v.split(" ").map(Number));
const visited = Array(N + 1).fill(false);
const graph = Array.from(Array(N + 1)).map(() => []);
let answer = 0;
const checkArr = [];
lines.map(([from, to]) => {
graph[from].push(to);
graph[to].push(from);
});
const bfs = (start) => {
let queue = [start];
while (queue.length) {
const node = queue.shift();
for (const vertax of graph[node]) {
if (!visited[vertax]) {
visited[vertax] = true;
queue.push(vertax);
}
}
}
};
for (let i = 1; i <= N; i++) {
if (visited[i]) continue;
bfs(i);
answer++;
}
return answer;
}
console.log(solution(input));
끝
728x90
'WEB > 백준 문제 풀이' 카테고리의 다른 글
백준 1261 알고스팟 (node.js) (0) | 2024.06.29 |
---|---|
백준 15723 n단 논법 (node.js) (0) | 2024.06.28 |
백준 16987 계란으로 계란치기 (node.js) (0) | 2024.06.24 |
백준 15686 연산자 끼워 넣기 (node.js) (0) | 2024.06.22 |
백준 15686 치킨 배달 (node.js) (0) | 2024.06.20 |