Algorithm&CodingTest/Baekjoon
[ Baekjoon ] [11724] DFS/BFS 실버 2 - 연결 요소의 개수
kitez
2023. 3. 14. 11:45
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