BFS: A - B - C - D - E - F
DFS: A - B - D - E - C - F
// 그래프로 구현
const graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B']
}
class Graph {
constructor(value) {
this.value = value;
}
bfs(graph, startNode) {...}
dfs(graph, startNode) {...}
}
const graphBfsDfs = new Graph();
graphBfsDfs.bfs(graph, "A");
graphBfsDfs.dfs(graph, "A");
bfs(graph, startNode) {
const visited = [];
let need_visit = [];
need_visit.push(startNode);
while (need_visit.length > 0) {
const currNode = need_visit.shift();
if (!visited.includes(currNode)) {
visited.push(currNode);
const nodeArr = Object.assign([], graph[currNode]);
//graph[currNode]는 객체여서 iterable하지 않아 배열로 바꿔줌
need_visit = [...need_visit, ...nodeArr];
}
}
console.log(visited); // [ 'A', 'B', 'C', 'D', 'E', 'F' ]
}
dfs(graph, startNode) {
const visited = [];
let need_visit = [];
need_visit.push(startNode);
while (need_visit.length > 0) {
const currNode = need_visit.shift();
if (!visited.includes(currNode)) {
visited.push(currNode);
const nodeArr = Object.assign([], graph[currNode]);
//graph[currNode]는 객체여서 iterable하지 않아 배열로 바꿔줌
need_visit = [...nodeArr, ...need_visit];
}
}
console.log(visited); // [ 'A', 'B', 'D', 'E', 'C', 'F' ]
}