Skip to content

Commit

Permalink
8-연결-요소의-개수
Browse files Browse the repository at this point in the history
  • Loading branch information
minbr0ther committed Feb 27, 2022
1 parent efe3933 commit be8f7e2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
44 changes: 44 additions & 0 deletions 2022/graph-traversal/8-연결 요소의 개수/app.js
@@ -0,0 +1,44 @@
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let input = fs.readFileSync(filePath).toString().trim().split("\n");

// 정점의 개수, 간선의 개수
const [N, M] = input.shift().split(" ").map(Number);
const edges = input.map((str) => str.split(" ").map(Number));

const graph = new Map();
Array.from({ length: N }, (_, i) => graph.set(i + 1, []));

edges.forEach((edge) => {
const [u, v] = edge;

graph.get(u).push(v);
graph.get(v).push(u);
});

let cnt = 0;
const visited = new Set();

const DFS = (current) => {
visited.add(current);

// i ~ next의 개수만큼
for (let i = 0; i < graph.get(current).length; i++) {
const next = graph.get(current)[i];

if (!visited.has(next)) {
DFS(next);
}
}
};

for (let i = 1; i <= N; i++) {
if (!visited.has(i)) {
DFS(i);
cnt++;
}
}

console.log(cnt);

// 출처: https://kscodebase.tistory.com/395
6 changes: 6 additions & 0 deletions 2022/graph-traversal/8-연결 요소의 개수/input.txt
@@ -0,0 +1,6 @@
6 5
1 2
2 5
5 1
3 4
4 6

0 comments on commit be8f7e2

Please sign in to comment.