백준_DFS와BFS_1260

Minji Lee·2024년 11월 4일
0

JS코딩테스트

목록 보기
78/122

DFS와 BFS

문제

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.

입력

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

출력

첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

예제 입력 1

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

예제 출력 1

1 2 4 3
1 2 3 4

예제 입력 2

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

예제 출력 2

3 1 2 5 4
3 1 4 2 5

Code

const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().split('\n');

const [N, M, V] = input[0].split(' ').map(Number); // N: 정점 개수, M: 간선 개수, V: 탐색 시작 정점 번호
const array = Array.from({ length: N + 1 }, () => []); // 인접리스트 생성
for (let i = 1; i <= M; i += 1) {
  const [a, b] = input[i].split(' ').map(Number);
  array[a].push(b);
  array[b].push(a);
}
array.forEach((a) => a.sort((a, b) => a - b)); // 각 인접리스트들 오름차순 정렬(방문할 수 있는 곳 여러개인 경우 작은 수부터 방문)

const dfsAnswer = []; // dfs 수행 결과
const dfsVisited = Array.from({ length: N + 1 }, () => false);
const bfsAnswer = []; // bfs 수행 결과
const bfsVisited = Array.from({ length: N + 1 }, () => false);

// dfs 함수
const dfs = (current) => {
  dfsAnswer.push(current);
  dfsVisited[current] = true;
  for (let item of array[current]) {
    if (!dfsVisited[item]) dfs(item);
  }
  return;
};

// bfs 함수
const bfs = (current) => {
  const queue = [];
  queue.push(current);
  bfsAnswer.push(current);
  bfsVisited[current] = true;
  while (queue.length > 0) {
    const item = queue.shift();
    for (let data of array[item]) {
      if (!bfsVisited[data]) {
        queue.push(data);
        bfsAnswer.push(data);
        bfsVisited[data] = true;
      }
    }
  }
  return;
};

dfs(V);
bfs(V);

console.log(...dfsAnswer);
console.log(...bfsAnswer);

풀이 및 해설

  1. 인접 리스트 만들기
  2. 각 인접 리스트 오름차순 정렬 ⇒ 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문
  3. V 부터 dfs랑 bfs 수행하며 정답 배열에 넣기

0개의 댓글