|
| 1 | +/** |
| 2 | + * Copyright (C) 2014 Tayllan Búrigo |
| 3 | + * |
| 4 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 5 | + * of this software and associated documentation files (the "Software"], to |
| 6 | + * deal in the Software without restriction, including without limitation the |
| 7 | + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or |
| 8 | + * sell copies of the Software, and to permit persons to whom the Software is |
| 9 | + * furnished to do so, subject to the following conditions: |
| 10 | + * |
| 11 | + * The above copyright notice and this permission notice shall be included in |
| 12 | + * all copies or substantial portions of the Software. |
| 13 | + * |
| 14 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 15 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 16 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 17 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 18 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 19 | + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
| 20 | + * IN THE SOFTWARE. |
| 21 | + */ |
| 22 | +'use strict'; |
| 23 | + |
| 24 | +var bellmanFord = require('../../../algorithms/graph/bellman_ford'), |
| 25 | + Graph = require('../../../data_structures/graph'), |
| 26 | + assert = require('assert'); |
| 27 | + |
| 28 | +describe('Bellman-Ford Algorithm', function () { |
| 29 | + it('should return the shortest paths to all nodes from a given origin', |
| 30 | + function () { |
| 31 | + var graph = new Graph(true); |
| 32 | + |
| 33 | + graph.addEdge('a', 'b', -1); |
| 34 | + graph.addEdge('a', 'c', 4); |
| 35 | + graph.addEdge('b', 'c', 3); |
| 36 | + graph.addEdge('b', 'd', 2); |
| 37 | + graph.addEdge('b', 'e', 2); |
| 38 | + graph.addEdge('d', 'b', 1); |
| 39 | + graph.addEdge('e', 'd', -3); |
| 40 | + graph.addEdge('d', 'c', 5); |
| 41 | + |
| 42 | + var shortestPaths = bellmanFord(graph, 'a'); |
| 43 | + |
| 44 | + assert.equal(shortestPaths.distance.a, 0); |
| 45 | + assert.equal(shortestPaths.distance.d, -2); |
| 46 | + assert.equal(shortestPaths.distance.e, 1); |
| 47 | + |
| 48 | + // It'll cause a Negative-Weighted Cycle. |
| 49 | + graph.addEdge('c', 'a', -9); |
| 50 | + |
| 51 | + shortestPaths = bellmanFord(graph, 'a'); |
| 52 | + |
| 53 | + // The 'distance' object is empty |
| 54 | + assert.equal(shortestPaths.distance.a, undefined); |
| 55 | + }); |
| 56 | +}); |
0 commit comments