From ae17d1b4a1c7ad20b442ae6ae85340936b08676c Mon Sep 17 00:00:00 2001 From: Eugene Sharygin Date: Sat, 26 Jul 2014 15:09:18 +0400 Subject: [PATCH] Add BFS shortest path algorithm --- algorithms/graph/bfs_shortest_path.js | 34 ++++++++++++++++ main.js | 1 + test/algorithms/graph/bfs_shortest_path.js | 45 ++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 algorithms/graph/bfs_shortest_path.js create mode 100644 test/algorithms/graph/bfs_shortest_path.js diff --git a/algorithms/graph/bfs_shortest_path.js b/algorithms/graph/bfs_shortest_path.js new file mode 100644 index 0000000..e583ebe --- /dev/null +++ b/algorithms/graph/bfs_shortest_path.js @@ -0,0 +1,34 @@ +'use strict'; + +var breadthFirstSearch = require('./breadth_first_search'); + + +/** + * Shortest-path algorithm based on Breadth-First Search. + * Works solely on graphs with equal edge weights (but works fast). + * Complexity: O(V + E). + * + * @param {Graph} graph + * @param {string} source + * @return {{distance: Object., + * previous: Object.}} + */ +var bfsShortestPath = function (graph, source) { + var distance = {}, previous = {}; + distance[source] = 0; + + breadthFirstSearch(graph, source, { + onTraversal: function (vertex, neighbor) { + distance[neighbor] = distance[vertex] + 1; + previous[neighbor] = vertex; + } + }); + + return { + distance: distance, + previous: previous + }; +}; + + +module.exports = bfsShortestPath; diff --git a/main.js b/main.js index 5c2a67f..9af2d9f 100644 --- a/main.js +++ b/main.js @@ -10,6 +10,7 @@ var lib = { depthFirstSearch: require('./algorithms/graph/depth_first_search'), kruskal: require('./algorithms/graph/kruskal'), breadthFirstSearch: require('./algorithms/graph/breadth_first_search'), + bfsShortestPath: require('./algorithms/graph/bfs_shortest_path'), }, Math: { fibonacci: require('./algorithms/math/fibonacci'), diff --git a/test/algorithms/graph/bfs_shortest_path.js b/test/algorithms/graph/bfs_shortest_path.js new file mode 100644 index 0000000..6e9258e --- /dev/null +++ b/test/algorithms/graph/bfs_shortest_path.js @@ -0,0 +1,45 @@ +'use strict'; + +var bfsShortestPath = require('../../../algorithms/graph/bfs_shortest_path'), + Graph = require('../../../data_structures/graph'), + assert = require('assert'); + + +describe('BFS Shortest Path Algorithm', function () { + it('should return the shortest paths to all nodes from a given origin', + function () { + var graph = new Graph(); + graph.addEdge(0, 1); + graph.addEdge(1, 2); + graph.addEdge(0, 2); + graph.addEdge(2, 3); + graph.addEdge(3, 6); + graph.addEdge(6, 2); + graph.addEdge(6, 0); + graph.addEdge(0, 4); + graph.addEdge(4, 6); + graph.addEdge(4, 5); + graph.addEdge(5, 0); + graph.addEdge('a', 'b'); + + var shortestPath = bfsShortestPath(graph, 0); + + assert.deepEqual(shortestPath.distance, { + 0: 0, + 1: 1, + 2: 1, + 3: 2, + 4: 1, + 5: 2, + 6: 2 + }); + assert.deepEqual(shortestPath.previous, { + 1: 0, + 2: 0, + 3: 2, + 4: 0, + 5: 4, + 6: 4 + }); + }); +});