From a49a48a9f5b471b51f4f8817c4daba2147e15d2d Mon Sep 17 00:00:00 2001 From: Eugene Sharygin Date: Mon, 28 Jul 2014 13:38:18 +0400 Subject: [PATCH] Return previous vertices in Bellman-Ford (as other shortest-path algorithms do) --- algorithms/graph/bellman_ford.js | 5 ++++- test/algorithms/graph/bellman_ford.js | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/algorithms/graph/bellman_ford.js b/algorithms/graph/bellman_ford.js index 475e9b8..7a468ec 100644 --- a/algorithms/graph/bellman_ford.js +++ b/algorithms/graph/bellman_ford.js @@ -15,6 +15,7 @@ */ var bellmanFord = function (graph, startNode) { var minDistance = {}; + var previousVertex = {}; var edges = []; var adjacencyListSize = 0; @@ -45,6 +46,7 @@ var bellmanFord = function (graph, startNode) { if (sourceDistance < targetDistance) { minDistance[edges[j].target] = sourceDistance; + previousVertex[edges[j].target] = edges[j].source; } } } @@ -63,7 +65,8 @@ var bellmanFord = function (graph, startNode) { } return { - distance: minDistance + distance: minDistance, + previous: previousVertex }; }; diff --git a/test/algorithms/graph/bellman_ford.js b/test/algorithms/graph/bellman_ford.js index b2f2a2d..fbc6f39 100644 --- a/test/algorithms/graph/bellman_ford.js +++ b/test/algorithms/graph/bellman_ford.js @@ -23,6 +23,8 @@ describe('Bellman-Ford Algorithm', function () { assert.equal(shortestPaths.distance.a, 0); assert.equal(shortestPaths.distance.d, -2); assert.equal(shortestPaths.distance.e, 1); + assert.equal(shortestPaths.previous.d, 'e'); + assert.equal(shortestPaths.previous.e, 'b'); // It'll cause a Negative-Weighted Cycle. graph.addEdge('c', 'a', -9);