그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.
첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "ex.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const [N, M, V] = input.shift().split(" ").map(Number);
const numbers = input.map((el) => el.split(" ").map(Number));
const graph = Array.from({ length: N + 1 }, () => []);
numbers.map(([from, to]) => {
graph[from].push(to);
graph[to].push(from);
});
graph.forEach((nodes) => nodes.sort((a, b) => a - b));
// DFS
function DFS(graph, startNode) {
const visited = [];
let needVisit = [];
needVisit.push(startNode);
while (needVisit.length !== 0) {
const node = needVisit.shift();
if (!visited.includes(node)) {
visited.push(node);
needVisit = [...graph[node], ...needVisit];
}
}
return visited;
}
// BFS
function BFS(graph, startNode) {
const visited = [];
let needVisit = [];
needVisit.push(startNode);
while (needVisit.length !== 0) {
const node = needVisit.shift();
if (!visited.includes(node)) {
visited.push(node);
needVisit = [...needVisit, ...graph[node]];
}
}
return visited;
}
const dfs = DFS(graph, V);
const bfs = BFS(graph, V);
console.log(dfs.join(" "));
console.log(bfs.join(" "));
초반에 계속 틀려서 왜 그런가 했는데 정점들을 오름차순으로 정렬
할 때 잘못해서 틀렸었다.
numbers의 2번째 숫자들을 기준으로 오름차순 정렬한 sorted_numbers
를 만들어 이걸 바탕으로 그래프를 만들었고, 이렇게 하면 정점들이 오름차순으로 정렬될 것이라 생각했는데 아니었다!!
sorted_numbers
가 아래와 같을 때, 양방향 그래프를 만들 것이기 때문에 2 -> 5,1 로 값이 들어가므로 오름차순이 아니게 된다.
[ [ 3, 1 ], [ 5, 2 ], [ 1, 2 ], [ 5, 4 ], [ 3, 4 ] ]
const [N, M, V] = input.shift().split(" ").map(Number);
const numbers = input.map((el) => el.split(" ").map(Number));
const sorted_numbers = numbers.sort((a, b) => a[1] - b[1]);
const graph = Array.from({ length: N + 1 }, () => []);
sorted_numbers.map(([from, to]) => {
graph[from].push(to);
graph[to].push(from);
});
따라서 양방향 그래프를 오름차순으로 탐색하기 위해서는 그래프에 값을 먼저 넣은 후에 그래프를 오름차순으로 정렬해야 한다.
DFS, BFS 참고