๐ŸŽฒ ๋ฐฑ์ค€ 1260๋ฒˆ DFS์™€ BFS

Jeongeunยท2023๋…„ 4์›” 24์ผ
0

๋ฐฑ์ค€

๋ชฉ๋ก ๋ณด๊ธฐ
55/185

๋ฐฑ์ค€ 1260๋ฒˆ

์ฝ”๋“œ

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

const info = input.shift().split(" ").map(Number);
const N = info[0];
const M = info[1];
const V = info[2];

//๊ทธ๋ž˜ํ”„ ๋งŒ๋“ค๊ธฐ
let graph = {};

for (let i = 0; i < N; i++) {
  graph[i + 1] = [];
}

for (let i = 0; i < M; i++) {
  const arr = input[i].split(" ").map(Number);
  graph[arr[0]].push(arr[1]);
  graph[arr[1]].push(arr[0]);
}

//DFS
let dfs = [];
let willDfs = [V];

while (willDfs.length !== 0) {
  const check = willDfs.shift();
  if (!dfs.includes(check)) {
    dfs.push(check);
    graph[check] = graph[check].sort((a, b) => a - b);
    willDfs.unshift(...graph[check]);
  }
}

console.log(dfs.join(" "));

//BFS
let bfs = [];
let willBfs = [V];

while (willBfs.length !== 0) {
  const check = willBfs.shift();
  if (!bfs.includes(check)) {
    bfs.push(check);
    graph[check] = graph[check].sort((a, b) => a - b);
    willBfs.push(...graph[check]);
  }
}

console.log(bfs.join(" "));

0๊ฐœ์˜ ๋Œ“๊ธ€