diff --git "a/2022/graph-traversal/8-\354\227\260\352\262\260 \354\232\224\354\206\214\354\235\230 \352\260\234\354\210\230/app.js" "b/2022/graph-traversal/8-\354\227\260\352\262\260 \354\232\224\354\206\214\354\235\230 \352\260\234\354\210\230/app.js" new file mode 100644 index 0000000..57b6939 --- /dev/null +++ "b/2022/graph-traversal/8-\354\227\260\352\262\260 \354\232\224\354\206\214\354\235\230 \352\260\234\354\210\230/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 diff --git "a/2022/graph-traversal/8-\354\227\260\352\262\260 \354\232\224\354\206\214\354\235\230 \352\260\234\354\210\230/input.txt" "b/2022/graph-traversal/8-\354\227\260\352\262\260 \354\232\224\354\206\214\354\235\230 \352\260\234\354\210\230/input.txt" new file mode 100644 index 0000000..ab256d3 --- /dev/null +++ "b/2022/graph-traversal/8-\354\227\260\352\262\260 \354\232\224\354\206\214\354\235\230 \352\260\234\354\210\230/input.txt" @@ -0,0 +1,6 @@ +6 5 +1 2 +2 5 +5 1 +3 4 +4 6 \ No newline at end of file