코딩연습
[백준 알고리즘] Node.js 1260. DFS와 BFS
니 뽀
2023. 6. 15. 14:08
1. 문제
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
2. 풀이
- DFS와 BFS를 사용하는 문제이다.
const inputs = require('fs').readFileSync('/dev/stdin').toString().trim().split('\n');
const [n,m,v] = inputs.shift().split(' ').map(v => +v);
const graph = Array.from(Array(n+1), () => [])
inputs.forEach(item => {
let [a,b] = item.split(' ').map(v => +v);
graph[a].push(b);
graph[b].push(a);
})
const dfsAnswer = [];
const dfsVisited = new Array(n).fill(false)
const dfs = (value) => {
dfsVisited[value] = true;
dfsAnswer.push(value)
const nodes = graph[value].sort((a,b) => a-b);
for(let node of nodes){
if(!dfsVisited[node]){
dfsVisited[node] = true;
dfs(node)
}
}
}
const bfs = (value) => {
const visited = [];
const queue = [];
queue.push(value);
while(queue.length){
let target = queue.shift();
if(!visited.includes(target)){
visited.push(target)
queue.push(...graph[target].sort((a,b) => a-b))
}
}
return visited;
}
dfs(v)
let returnVal = bfs(v)
console.log(dfsAnswer.join(' '))
console.log(returnVal.join(' '))
- bfs와 dfs 를 조금 다르게 풀었다. 좀 더 연습해봐야겠다.