Skip to content

Commit

Permalink
Merge pull request #78 from eush77/bfs-shortest-path
Browse files Browse the repository at this point in the history
Add shortest path algorithm based on Breadth-First Search
  • Loading branch information
felipernb committed Jul 28, 2014
2 parents 51a9fff + ae17d1b commit 1f00a35
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
34 changes: 34 additions & 0 deletions algorithms/graph/bfs_shortest_path.js
Original file line number Diff line number Diff line change
@@ -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.<string, number>,
* previous: Object.<string, string>}}
*/
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;
1 change: 1 addition & 0 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down
45 changes: 45 additions & 0 deletions test/algorithms/graph/bfs_shortest_path.js
Original file line number Diff line number Diff line change
@@ -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
});
});
});

0 comments on commit 1f00a35

Please sign in to comment.