https://www.acmicpc.net/problem/11724
11724번: 연결 요소의 개수
첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주
www.acmicpc.net
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split("\n");
const [N, M] = input.shift().split(" ").map( i => Number(i));
const graph = new Array(N+1).fill(0).map(i => []);
let V = new Array(N+1).fill(false);
input.forEach((i) => {
const [to, from] = i.split(" ").map(n => Number(n));
graph[to].push(from);
graph[from].push(to);
});
const dfs = (start) => {
const visited = [];
let stack = [start];
while(stack.length) {
const cur = stack.pop();
if(!visited.includes(cur)) {
visited.push(cur);
V[cur] = true;
stack.push(...graph[cur]);
graph[cur].length = 0;
}
}
return visited;
}
let start = 1;
let cnt = 0;
while(start !== graph.length) {
if(graph[start].length) {
dfs(start);
cnt++;
}
start++;
}
V = V.filter(v => !v);
console.log(V.length > 1 ? cnt+V.length-1 : cnt);
728x90
'Algorithm&CodingTest > Baekjoon' 카테고리의 다른 글
[Baekjoon] [1766] 위상정렬 골드2 - 문제집 (0) | 2023.03.15 |
---|---|
[Baekjoon] [2667] DFS/BFS 실버 1 - 단지번호붙이기 (0) | 2023.03.14 |
[ Baekjoon ] [1260] DFS/BFS 실버 2 - DFS와 BFS (0) | 2023.03.13 |
[ Baekjoon ] [1049] 그리디 실버3 - 기타줄 (0) | 2023.03.13 |
[ Baekjoon ] [2607] 실버 3 - 비슷한 단어 (1) | 2023.03.12 |