// Original answer by Tepinly
function Graph() {
this.nodes = [];
}
function Node(val) {
this.val = val;
this.edges = [];
}
// Add ass many nodes as you want at once
Graph.prototype.addNodes = function (...val) {
for (i of val) {
this.nodes.push(new Node(i));
}
};
// Add edges to each node
Graph.prototype.addEdges = function (val, ...edges) {
const node = this.nodes.find((i) => i.val === val);
for (edgeVal of edges) {
node.edges.push(this.nodes.find((i) => i.val === edgeVal));
}
};
// BFS algorithm
Graph.prototype.bfs = function (root) {
let node = this.nodes.find((i) => i.val === root);
const queue = [root];
const visited = [];
while (queue.length > 0) {
current = queue.pop();
if (visited.includes(current)) continue;
visited.push(current);
node = this.nodes.find((i) => i.val === current);
console.log(node.val);
for (i of node.edges) {
if (!visited.includes(i.val)) queue.unshift(i.val);
}
}
};
// DFS algorithm
Graph.prototype.dfs = function (root, visited = []) {
if (!visited.includes(root)) {
visited.push(root);
console.log(root);
const node = this.nodes.find((i) => i.val === root);
for (i of node.edges) this.dfs(i.val, visited);
}
};
const graph = new Graph();
graph.addNodes(0, 1, 2, 3, 4);
graph.addEdges(0, 1, 2, 3);
graph.addEdges(1, 4);
graph.addEdges(4, 3, 1);
// 0 -> 1, 2, 3
// 1 -> 4
// 4 -> 3, 1
graph.dfs(0);
// DFS: 0, 1, 4, 3, 2
// BFS: 0, 1, 2, 3, 4