Algorithm&CodingTest/Baekjoon
[ Baekjoon ] [1260] DFS/BFS 실버 2 - DFS와 BFS
kitez
2023. 3. 13. 10:54
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 fs = require('fs');
const input = fs.readFileSync('./7568.txt').toString().trim().split("\n");
const [N, M ,V] = input.shift().split(" ").map( i => Number(i));
const graph = new Array(N+1).fill(0).map( i => []);
input.forEach((i) => {
const [e0, e1] = i.split(" ").map( d => Number(d));
graph[e0].push(e1);
graph[e1].push(e0);
});
const dfs = (start) => {
const visited = [];
const stack = [start];
while(stack.length) {
const current = stack.pop();
if(!visited.includes(current)) {
visited.push(current);
stack.push(...graph[current]);
}
}
return visited;
}
const bfs = (start) => {
const visited = [];
const queue = [start];
while(queue.length) {
const current = queue.shift();
if(!visited.includes(current)) {
visited.push(current);
queue.push(...graph[current]);
}
}
return visited;
}
graph.forEach(v => v.sort((a, b) => b - a));
console.log(dfs(V).join(" "));
graph.forEach(v => v.sort((a, b) => a - b));
console.log(bfs(V).join(" "));
728x90