โถ ๋ฌธ์ : https://www.acmicpc.net/problem/11724
โถ ์ฝ๋ :
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let N = 0;
let E = 0;
const edges = [];
rl.on('line', function(line) {
if(!N){
[N, E] = line.split(' ').map(Number);
if(E === 0){
main();
process.exit();
}
}else{
edges.push(line);
if(edges.length === E){
main();
process.exit();
}
}
});
const main = () => {
const graph = Array.from(Array(N), () => Array().fill([]));
for (let i = 0; i < E; i++){
const [x,y] = edges[i].split(' ').map(n => Number(n));
graph[x-1].push(y-1);
graph[y-1].push(x-1);
}
const visited = Array(N).fill(false);
let count = 0;
for(let i = 0; i < N; i++){
if(visited[i]){
continue;
}else{
dfs(graph,visited,i);
count+=1;
}
}
console.log(count);
function dfs(graph, visited, start){
visited[start] = true;
const stack = [...graph[start]]
while(stack.length > 0){
const node = stack.pop();
if(visited[node]){
continue;
}
visited[node] = true;
stack.push(...graph[node]);
}
}
}
โถ ๋ฌธ์ ํ์ด :
1. ๋๋ฌด ๋ณต์กํ๊ณ ์ด๋ ต๊ฒ ํ์๋ค. ์ด๊ธฐ fs ๋ก ๋ฐ์ดํฐ๋ฅผ ์ฝ๊ณ ์คํ๋ ๋ ๋ฌธ๋ฒ(...)์ ๋์ฌํ๋ฉด์ ํ์๋ ์ฝ๋์์ํด ๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ๊ฐ ๊ณ์ ๋ฐ์ํ๋ค.
2. ์คํ๋ ๋(...) ๋ฌธ๋ฒ์ ๊ธฐ์กด ๋ฐฐ์ด์ ์ชผ๊ฐ ์๋ก์ด ๋ฐฐ์ด์ ๋ฐํํ๊ธฐ์ ๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ๊ฐ ๋๋(?) ๋ผ๋ ์์ฌ์ ํ๊ฒ ๋์๊ณ , ์คํ๋ ๋ ๋ฌธ๋ฒ์ ์ฌ์ฉํ ๋ถ๋ถ์ ์ค์ฌ๋ณด์ ํด์ ๋ค์๊ธ ์์ฑํ๊ฒ ๋์๋ค. ๋ํ ์ ์ถ๋ ฅ ๋ฐฉ์์ ๋ฌธ์ ๊ฐ ์๋ ๊ฒ ๊ฐ๊ธฐ๋ ํด์ fs์์ readline์ ์ด์ฉํ ๋ฐฉ์์ผ๋ก ๋ณ๊ฒฝํด๋ณด์๋ค.
3. ์ด๊ธฐ readline์ ํตํด ์ฝ์ด์จ ๋ฐ์ดํฐ๋ฅผ ํ์ฑํด N, E, edges[] ๋ฅผ ์ด๊ธฐํํ๊ณ main ๋ฉ์๋์์ ๋ก์ง์ ์ฒ๋ฆฌํ๋ค.
4. main๋ฌธ์์๋ edge๋ฐ์ดํฐ๋ฅผ ์ฝ์ด ๊ทธ๋ํ๋ฅผ ์์ฑํ๊ณ ๋ด๋ถ ์ ์ํจ์ dfs()๋ฅผ ์ด์ฉํด ๊ทธ๋ํ๋ค์ ํ์ํ๋ค. ๊ฒฐ๊ตญ dfs์ ์ํด visited๋ฐฐ์ด์ ํ๋ฒ์ฉ ๋ณํ๊ฐ ์๊ธฐ๊ณ dfs๋ฅผ ํธ์ถํ ๋๋ง๋ค count๋ฅผ 1์ฉ ์ฆ๊ฐ์ํค๋ ๋ฐฉ์์ ์ฑํํ์๋ค.
5. ๋๋ฌด ์ค๋๊ฑธ๋ ธ์ง๋ง ๊ทธ๋๋ ํด๊ฒฐํ์์ ๋ฟ๋ฏํ๊ณ ๋ค๋ฅธ ๋ถ๋ค์ ์ฝ๋๋ฅผ ๋ณด๋ค๊ฐ ์กฐ๊ธ ๋ ๊น๋ํ๊ณ , ์ดํด๊ฐ ์๋๋ ์ฝ๋๊ฐ ์์๊ธฐ์ ๊ฐ์ ธ์ ๋ณด์๋ค.
โถ ๋ค๋ฅธ ์ ์ ์ ํ์ด๋ฐฉ๋ฒ:
const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const [n, m] = input.shift().split(' ').map(Number);
const arr = input.map((el) => el.split(' ').map(Number));
const solution = (n, arr) => {
let answer = 0;
let visited = Array.from(Array(n + 1), () => 0);
const graph = Array.from(Array(n + 1), () => []);
for (let [a, b] of arr) {
graph[a].push(b);
graph[b].push(a);
}
const dfs = (node) => {
visited[node] = 1;
for (let next of graph[node]) {
if (!visited[next]) {
dfs(next);
}
}
};
for (let i = 1; i <= n; i++) {
if (!visited[i]) {
dfs(i);
answer++;
}
}
return answer;
};
console.log(solution(n, arr));
'๐ฏ CodingTest > BaekJoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BaekJoon] 17626๋ฒ Four Squares (0) | 2022.06.03 |
---|---|
[BaekJoon] 17219๋ฒ ๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ (0) | 2022.06.03 |
[BaekJoon] 2606๋ฒ ๋ฐ์ด๋ฌ์ค (0) | 2022.06.02 |
[BaekJoon] 2579๋ฒ ๊ณ๋จ ์ค๋ฅด๊ธฐ (0) | 2022.06.02 |
[Baekjoon] 1764 ๋ฃ๋ณด์ก (0) | 2022.05.27 |