πŸ’‘λ¬Έμ œ 뢄석 μš”μ•½

πŸ’‘μ•Œκ³ λ¦¬μ¦˜ 섀계

πŸ’‘μ½”λ“œ

const fs = require('fs');
const path = require('path');

const input = fs.readFileSync(path.join(__dirname, 'input.txt')).toString().trim().split('\\n');

// μž…λ ₯ λ°›κΈ°
const [N, M, V] = input[0].split(' ').map(Number);
const graph = Array.from({ length: N + 1 }, () => []); // μ •μ μ˜ 개수만큼 λ°°μ—΄ 생성

for (let i = 1; i <= M; i++) {
  const [a, b] = input[i].split(' ').map(Number);
  graph[a].push(b); // μ–‘λ°©ν–₯ κ·Έλž˜ν”„μ΄λ―€λ‘œ μ–‘μͺ½μ— μ—°κ²°
  graph[b].push(a);
}

// 정점 λ²ˆν˜Έκ°€ μž‘μ€ μˆœμ„œλŒ€λ‘œ λ°©λ¬Έν•΄μ•Ό ν•˜λ―€λ‘œ μ •λ ¬
graph.forEach((adjList) => adjList.sort((a, b) => a - b));

// DFS ν•¨μˆ˜ (μž¬κ·€μ  방식)
const dfs = (start, visited) => {
  visited[start] = true;
  process.stdout.write(start + ' '); // 탐색 μˆœμ„œ 좜λ ₯

  for (const neighbor of graph[start]) {
    if (!visited[neighbor]) {
      dfs(neighbor, visited);
    }
  }
};

// BFS ν•¨μˆ˜ (큐 방식)
const bfs = (start) => {
  const visited = Array(N + 1).fill(false);
  const queue = [start];
  visited[start] = true;

  while (queue.length) {
    const node = queue.shift(); // νμ—μ„œ κΊΌλ‚Έ λ…Έλ“œλ₯Ό λ°©λ¬Έ
    process.stdout.write(node + ' ');

    for (const neighbor of graph[node]) {
      if (!visited[neighbor]) {
        visited[neighbor] = true;
        queue.push(neighbor); // 큐에 인접 λ…Έλ“œ μΆ”κ°€
      }
    }
  }
};

// DFS 탐색
const visitedDFS = Array(N + 1).fill(false);
dfs(V, visitedDFS);
process.stdout.write('\\n');

// BFS 탐색
bfs(V);

πŸ’‘μ‹œκ°„ λ³΅μž‘λ„