Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Last active July 12, 2022 03:52
Show Gist options
  • Save CarlaTeo/89496c79469fe580fe34c2c26f86052c to your computer and use it in GitHub Desktop.
Save CarlaTeo/89496c79469fe580fe34c2c26f86052c to your computer and use it in GitHub Desktop.
[JS] Depth First Search and Breadth First Search
class Node {
constructor(value, children = []) {
this.value = value;
this.children = children;
}
}
// 3 --->7
// / | |
// 2 6-->2---0
// \ /
// 1
const node3 = new Node(3);
const node2 = new Node(2);
const node6 = new Node(6);
const node7 = new Node(7);
const node1 = new Node(1);
const node2b = new Node(2);
const node0 = new Node(0);
node3.children = [node2, node6, node7];
node2.children = [node3, node1];
node1.children = [node2, node6];
node6.children = [node3, node1, node2b];
node7.children = [node3, node2];
node2b.children = [node0, node6, node7];
node0.children = [node2];
function DFS(node, visited = new Set(), result = []) {
if(!node) return result;
result.push(node.value);
visited.add(node);
node.children.forEach(child => {
if(!visited.has(child)) result = DFS(child, visited, result);
})
return result;
}
console.log(DFS(node3)); // 3,2,1,6,2,0,7
function BFS(node) {
if(!node) return [];
const result = [];
const visited = new Set([node]);
const queue = [node];
while(queue.length) {
const current = queue.shift();
result.push(current.value);
current.children.forEach(child => {
if(!visited.has(child)) {
queue.push(child);
visited.add(child);
}
});
}
return result;
}
console.log(BFS(node3)); // 3,2,6,7,1,2,0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment