Tesseractjh
한 걸음씩
Tesseractjh
전체 방문자
오늘
어제
  • 전체 (293)
    • IT (30)
      • JavaScript (7)
      • TypeScript (5)
      • React (5)
      • Next.js (3)
      • MongoDB (2)
      • Webpack (2)
      • HTML & CSS (1)
      • Git (0)
      • AWS (1)
      • 기타 (4)
    • 연습장 (259)
      • 백준(BOJ) 문제풀이 (185)
      • 프로그래머스 문제풀이 (61)
      • LeetCode 문제풀이 (2)
      • HackerRank 문제풀이 (7)
      • 낙서장 (3)
      • 기타 (1)
    • 프로젝트 (3)
      • 지뢰피하기 (1)
      • 키릴-라틴 문자 변환기 (1)
      • Flex & Grid (1)
    • 멋쟁이사자처럼 프론트엔드 스쿨 1기 (1)
      • 일기 & 회고록 (1)

인기 글

티스토리

hELLO · Designed By 정상우.
Tesseractjh

한 걸음씩

[백준 1260 - Node.js] DFS와 BFS
연습장/백준(BOJ) 문제풀이

[백준 1260 - Node.js] DFS와 BFS

2022. 6. 3. 15:43

🔗 문제 링크

https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

✏️ 풀이

const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const [N, M, V] = input.shift().split(' ').map(Number);
const edges = input.map(v => v.split(' ').map(Number));
const graph = [...Array(N + 1)].map(() => []);
edges.forEach(([from, to]) => {
  graph[from].push(to);
  graph[to].push(from);
});

const dfs = (start) => {
  const stack = [start];
  const visited = Array(N + 1).fill(false);
  const order = [];
  while (stack.length) {
    const node = stack.pop();
    if (!visited[node]) {
      visited[node] = true;
      order.push(node);
      stack.push(...graph[node]);
    }
  }
  return order.join(' ');
};

const bfs = (start) => {
  const queue = [start];
  const visited = Array(N + 1).fill(false);
  const order = [];
  while (queue.length) {
    const node = queue.shift();
    if (!visited[node]) {
      visited[node] = true;
      order.push(node);
      queue.push(...graph[node]);
    }
  }
  return order.join(' ');
};

graph.forEach(v => v.sort((a, b) => b - a));
console.log(dfs(V));

graph.forEach(v => v.sort((a, b) => a - b));
console.log(bfs(V));

DFS는 stack을 이용하기 때문에 stack의 뒤에서부터 탐색을 한다는 점을 이용하여 graph의 모든 인접 노드들을 내림차순 정렬한 후에 DFS를 실행하였다.

BFS의 경우는 queue를 이용하기 때문에 앞에서부터 정방향으로 탐색하므로, graph의 모든 인접 노드들을 오름차순 정렬한 후에 BFS를 실행하였다.

 

 

🗃️ 다른 언어로 된 풀이

[백준 1260] DFS와 BFS with Python

저작자표시 비영리 (새창열림)

'연습장 > 백준(BOJ) 문제풀이' 카테고리의 다른 글

[백준 1012 - Node.js] 유기농 배추  (0) 2022.06.27
[백준 2573 - Node.js] 빙산  (0) 2022.06.05
[백준 16234 - Node.js] 인구 이동  (0) 2022.05.31
[백준 1707 - Node.js] 이분 그래프  (0) 2022.05.26
[백준 1520 - Node.js] 내리막길  (0) 2022.05.22
    '연습장/백준(BOJ) 문제풀이' 카테고리의 다른 글
    • [백준 1012 - Node.js] 유기농 배추
    • [백준 2573 - Node.js] 빙산
    • [백준 16234 - Node.js] 인구 이동
    • [백준 1707 - Node.js] 이분 그래프
    Tesseractjh
    Tesseractjh
    바닐라 자바스크립트를 좋아하는 개발자입니다

    티스토리툴바