문제
제한사항
입출력 예
풀이
const input = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const [n, m, startNode] = input.shift().split(' ').map(Number);
const arr = input.map((el) => el.split(' ').map(Number));
const solution = (n, startNode, arr) => {
let answer = [];
let visited = Array.from(Array(n + 1), () => 0);
const graph = Array.from(Array(n + 1), () => []);
for (let [a, b] of arr) {
graph[a].push(b);
graph[b].push(a);
}
graph.map((e) => e.sort((a, b) => a - b));
let tmp = '';
const dfs = (node) => {
visited[node] = 1;
tmp += node + ' ';
for (let next of graph[node]) {
if (!visited[next]) {
dfs(next);
}
}
};
dfs(startNode);
answer.push(tmp.trim());
let visited2 = Array.from(Array(n + 1), () => 0);
tmp = `${startNode} `;
const bfs = (node) => {
const queue = [];
visited2[node] = 1;
queue.push(node);
while (queue.length) {
let cur = queue.shift();
for (let next of graph[cur]) {
if (!visited2[next]) {
visited2[next] = 1;
queue.push(next);
tmp += next + ' ';
}
}
}
};
bfs(startNode);
answer.push(tmp.trim());
return answer.join('\n');
};
console.log(solution(n, startNode, arr));
- 이상하게 애를 먹었다.
- 함수를 나눴으면 좀 더 예뻣을텐데 나중에 시도해보자.