๐ฅ Algorithm/Baekjoon
[๋ฐฑ์ค 1260๋ฒ] DFS์ BFS - ์๋ฐ์คํฌ๋ฆฝํธ(nodejs)
Lennon
2022. 3. 18. 18:21
728x90
๋ฐ์ํ
https://www.acmicpc.net/problem/1260
const { off } = require('process');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
class Graph {
constructor() {
this.node = {};
}
addVertex(vertex) {
if (!this.node[vertex]) {
this.node[vertex] = [];
}
}
addEdge(v1, v2) {
this.node[v1].push(v2);
this.node[v2].push(v1);
}
depthFirstSearch(start) {
const result = [];
const visited = {};
const node = this.node;
function dfs(vertex) {
if (!vertex) return;
result.push(vertex);
visited[vertex] = true;
node[vertex]
.sort((a, b) => a - b)
.forEach((v) => {
if (!visited[v]) {
visited[v] = true;
return dfs(v);
}
});
}
dfs(start);
return result;
}
breadthFirstSearch(start) {
const queue = [start];
const result = [];
const visited = {};
visited[start] = true;
while (queue.length) {
const value = queue.shift();
result.push(value);
this.node[value]
.sort((a, b) => a - b)
.forEach((v) => {
if (!visited[v]) {
visited[v] = true;
queue.push(v);
}
});
}
return result;
}
}
let input = [];
rl.on('line', function (line) {
input.push(line);
if (input.length === +input[0].split(' ')[1] + 1) {
rl.close();
}
}).on('close', function () {
const [num, ver, start] = input.shift().split(' ');
const vertex = input.map((v) => v.split(' ').map(Number));
const graph = new Graph();
for (let i = 1; i <= +num; i++) {
graph.addVertex(i);
}
vertex.sort((a, b) => a[0] - b[0]);
vertex.forEach((v) => {
graph.addEdge(v[0], v[1]);
});
console.log(graph.depthFirstSearch(start).join(' '));
console.log(graph.breadthFirstSearch(start).join(' '));
});
์ค์ํ ๊ฑด ์ ์๋ ๊ฐ์ ๋ค์ ์ ๋ ฌํ๊ณ , ๊ฐ์ ์ ๋ฃ์ ๊ฐ์ฒด ๋ด๋ถ์์๋ ์ค๋ฆ์ฐจ์์ผ๋ก ์ ๋ ฌ๋ ์ํ์ฌ์ผ ๋๋ค!
(์๋๋ฉด ์์ ๊ฐ ๋ง๊ณ , ์ง๋ฌธํ๊ธฐ์ ์๋ ๋ฐ๋ก๊ฐ ๋ง๋ ๊ณ์ ํ๋ฆฝ๋๋ค.)
์ฐ์ ๊ฐ์ ์ ์ซ์๋ณ๋ก ์ ๋ ฌํด์ ๊ฐ์ ๋ฃ์ด์ค๋ค.
Graph {
node: {
'1': [ 2, 3 ],
'2': [ 1, 5 ],
'3': [ 4, 1 ],
'4': [ 3, 5 ],
'5': [ 4, 2 ]
}
}
๊ทธ๋ฆฌ๊ณ bfs, dfs๋ฅผ ์ํํ ๋ ํด๋น ๊ฐ์ ๋ค์ ๋ฐฐ์ด์ ์ค๋ฆ์ฐจ์์ผ๋ก sortํด์ฃผ๋ฉด์ ํ๋ฉด ๋๋ค.
728x90
๋ฐ์ํ