[백준] 11724 연결 요소의 개수 Node.js (DFS/BFS 풀이)

Janet·2023년 5월 9일
1

Algorithm

목록 보기
184/314

문제

방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주어진다.

출력

첫째 줄에 연결 요소의 개수를 출력한다.

예제 입력 1

6 5
1 2
2 5
5 1
3 4
4 6

예제 출력 1

2

예제 입력 2

6 8
1 2
2 5
5 1
3 4
4 6
5 4
2 4
2 3

예제 출력 2

1

문제풀이

✅ 답안 #1 : DFS - 재귀함수를 이용한 풀이

const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
const input = require('fs').readFileSync(filePath).toString().trim().split('\n');
const [N, M] = input.shift().split(' ').map(Number); // [정점의 개수, 간선의 개수]
const arr = input.map((v) => v.split(' ').map(Number));
let visited = Array(N + 1).fill(false);
let graph = [...Array(N + 1)].map(() => []);
let answer = 0;

// 양방향(무방향) 그래프로 만들기
arr.map(([from, to]) => {
  graph[from].push(to);
  graph[to].push(from);
});

const dfs = (start) => {
  for (const vertax of graph[start]) {
    if (!visited[vertax]) {
      visited[start] = true;
      dfs(vertax);
    }
  }
};

for (let i = 1; i <= N; i++) {
  if (!visited[i]) {
    dfs(i);
    answer++;
  }
}
console.log(answer);

✅ 답안 #2 : BFS - Queue 를 이용한 풀이

const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
const input = require('fs').readFileSync(filePath).toString().trim().split('\n');
const [N, M] = input.shift().split(' ').map(Number); // [정점의 개수, 간선의 개수]
const arr = input.map((v) => v.split(' ').map(Number));
let visited = Array(N + 1).fill(false);
let graph = [...Array(N + 1)].map(() => []);
let answer = 0;

arr.map(([from, to]) => {
  graph[from].push(to);
  graph[to].push(from);
});

const bfs = (start) => {
  let queue = [start];
  while (queue.length) {
    const cur = queue.shift();
    for (const vertax of graph[cur]) {
      if (!visited[vertax]) {
        visited[vertax] = true;
        queue.push(vertax);
      }
    }
  }
};

for (let i = 1; i <= N; i++) {
  if (!visited[i]) {
    bfs(i);
    answer++;
  }
}
console.log(answer);
profile
😸

1개의 댓글

comment-user-thumbnail
2023년 5월 15일

너무 좋은 풀이 잘봤습니다! 코드가 정말 깔끔하고 잘쓰신 것 같아서 많이 배워갑니다... 특히나 리눅스 환경을 확인해서 어디서 테케를 읽어올지 보는 부분이 정말 신기했습니다. 감사합니다!!

답글 달기