Skip to content
This repository was archived by the owner on Sep 7, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions graphs/bfs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
A non-recursive implementation of bfs with worst-case space complexity O(|E|)
*/

function Vertex (name, neighbours) {
this.name = name;
this.neighbours = neighbours;
}

function bfs (root) {
var visited = {}
var stack = []

stack.push(root)
while(!!stack.length) {
var vertex = stack.shift()

if (!visited[vertex.name]) {
visited[vertex.name] = true
console.log('Visiting vertex ', vertex.name)

var len = vertex.neighbours.length
for (var index = 0; index < len; index++) {
stack.push(vertex.neighbours[index])
}
}
}
}

var root = new Vertex('root', [
new Vertex('child 1', [
new Vertex('grandchild 1', []), new Vertex('grandchild 2', [])
]),
new Vertex('child 2', [
new Vertex('grandchild 3', []),
]),
new Vertex('child 3', [
new Vertex('grandchild 4', [
new Vertex('grandgrandchild 1', [])
]),
]),
])

bfs(root)
46 changes: 46 additions & 0 deletions graphs/dfs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
A non-recursive implementation of DFS with worst-case space complexity O(|E|)

according to wiki pseudocode https://en.wikipedia.org/wiki/Depth-first_search
*/

function Vertex (name, neighbours) {
this.name = name;
this.neighbours = neighbours;
}

function dfs (root) {
var visited = {}
var stack = []

stack.push(root)
while(!!stack.length) {
var vertex = stack.pop()

if (!visited[vertex.name]) {
visited[vertex.name] = true
console.log('Visiting vertex ', vertex.name)

var len = vertex.neighbours.length
for (var index = 0; index < len; index++) {
stack.push(vertex.neighbours[index])
}
}
}
}

var root = new Vertex('root', [
new Vertex('child 1', [
new Vertex('grandchild 1', []), new Vertex('grandchild 2', [])
]),
new Vertex('child 2', [
new Vertex('grandchild 3', []),
]),
new Vertex('child 3', [
new Vertex('grandchild 4', [
new Vertex('grandgrandchild 1', [])
]),
]),
])

dfs(root)