🔗 문제 링크
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를 실행하였다.
🗃️ 다른 언어로 된 풀이
'연습장 > 백준(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 |