Skip to content

Instantly share code, notes, and snippets.

@stivio00
Created May 19, 2022 21:41
Show Gist options
  • Save stivio00/938dc4e8e1863aa0592b0d2eb13ae2b2 to your computer and use it in GitHub Desktop.
Save stivio00/938dc4e8e1863aa0592b0d2eb13ae2b2 to your computer and use it in GitHub Desktop.
bfs dfs in js
// adj list graph representation:
const g = {
1: [2,3],
2: [4,3],
3: [5],
4: [1],
5: []
};
function bfs(g, start, func) {
const queue = [];
const visited = new Set();
queue.unshift(start); //enqueue in the queue
while (queue.length > 0) {
let current = queue.pop(); //dequeu
func(current);
visited.add(current);
g[current].forEach(e => {
if (!visited.has(e) && !queue.includes(e)) {
queue.unshift(e); // enqueue
}
});
}
}
function dfs_recursive(g, start, func, visited = null){
if (visited == null)
visited = new Set(); //HashSet
if (visited.has(start)) return;
func(start);
visited.add(start);
for (const e of g[start]) {
dfs_recursive(g, e, func, visited);
}
}
function dfs(g, start, func){
const visited = new Set(); //HashSet in java /c#
const stack = [];
stack.push(start);
while(stack.length > 0) {
let current = stack.pop();
func(current);
visited.add(current);
g[current].forEach(e => {
if (!visited.has(e)) {
stack.push(e);
}
});
}
}
console.log('bfs queue based alg');
bfs(g, 1, console.log);
console.log('dfs recursive based alg');
dfs_recursive(g, 1, console.log);
console.log('dfs stack based alg');
dfs(g, 1, console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment