๐ ์ฒ์์ ์๊ฐ์ด๊ณผ๊ฐ ๋ฐ์ํ๋๋ฐ BFS๋ก ํ๊ธฐ์ํด shift๋ฅผ ์ฌ์ฉํด์ ๊ทธ๋ฐ๋ฏํ๋ค. ๊ทธ๋์ DFS๋ก ํ์๋ค.
๐ ๋ฐ๊พผ ํ์๋ ํ๋ ธ๋ค๊ณ ํด์ ์ฐพ์๋ณด๋ graph์ ๋ณด๋ฅผ ๋ฃ์ ๋, (1,2), (2,1) ๋๋ค ๋ฃ์ด์ฃผ์ด์ผํ๋๋ฐ (1,2)๋ง ๋ฃ์ด์ฃผ์ด์ ๊ทธ๋ฐ ๊ฒ์ด์๋ค.
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const [N, M] = input.shift().split(" ").map(Number);
const graph = Array.from(new Array(N + 1), () => []);
for (let i = 0; i < M; i++) {
const [u, v] = input[i].split(" ").map(Number);
graph[u].push(v);
graph[v].push(u);
}
let checked = new Array(N + 1).fill(0);
let willCheck = [];
let block = 0;
const DFS = () => {
while (willCheck.length) {
const check = willCheck.pop();
if (checked[check] === 0) {
checked[check] = 1;
for (let i = 0; i < graph[check].length; i++) {
willCheck.push(graph[check][i]);
}
}
}
};
for (let i = 1; i < N + 1; i++) {
if (checked[i] === 0) {
willCheck.push(i);
DFS();
block++;
}
}
console.log(block);