From 4a17a23cc583a112a497df3cb8777351eccaa320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Karabu=C5=82a-Stysiak?= Date: Tue, 2 Oct 2018 13:56:53 +0200 Subject: [PATCH] Add DFS and BFS algorithms --- graphs/bfs.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ graphs/dfs.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 graphs/bfs.js create mode 100644 graphs/dfs.js diff --git a/graphs/bfs.js b/graphs/bfs.js new file mode 100644 index 0000000..96f6348 --- /dev/null +++ b/graphs/bfs.js @@ -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) diff --git a/graphs/dfs.js b/graphs/dfs.js new file mode 100644 index 0000000..bcbfe8e --- /dev/null +++ b/graphs/dfs.js @@ -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)