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(" "));
'Algorithm&CodingTest > Baekjoon' 카테고리의 다른 글
[Baekjoon] [2667] DFS/BFS 실버 1 - 단지번호붙이기 (0) | 2023.03.14 |
---|---|
[ Baekjoon ] [11724] DFS/BFS 실버 2 - 연결 요소의 개수 (0) | 2023.03.14 |
[ Baekjoon ] [1049] 그리디 실버3 - 기타줄 (0) | 2023.03.13 |
[ Baekjoon ] [2607] 실버 3 - 비슷한 단어 (1) | 2023.03.12 |
[ Baekjoon ] [13305] 실버 3 - 주유소 (0) | 2023.03.12 |