From 6fa94be9a78448cbcb1d1c4d3815326442596755 Mon Sep 17 00:00:00 2001 From: 27Anurag <56363215+27Anurag@users.noreply.github.com> Date: Tue, 8 Dec 2020 00:46:43 +0530 Subject: [PATCH] Added bellmanFord funtion In javascript --- apsp.js | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 apsp.js diff --git a/apsp.js b/apsp.js new file mode 100644 index 0000000..c3bd448 --- /dev/null +++ b/apsp.js @@ -0,0 +1,47 @@ +/** + * @param {Graph} graph + * @param {GraphVertex} startVertex + * @return {{distances, previousVertices}} + */ + + +export default function bellmanFord(graph, startVertex) { + const distances = {}; + const previousVertices = {}; + + + distances[startVertex.getKey()] = 0; //starting node + + graph.getAllVertices().forEach((vertex) => { + previousVertices[vertex.getKey()] = null; + if (vertex.getKey() !== startVertex.getKey()) { + distances[vertex.getKey()] = Infinity; //init all dists with infinity + } + }); + + // We need (|V| - 1) iterations. + for (let iteration = 0; iteration < (graph.getAllVertices().length - 1); iteration += 1) { + + Object.keys(distances).forEach((vertexKey) => { + const vertex = graph.getVertexByKey(vertexKey); + + // Go through all vertex edges. + graph.getNeighbors(vertex).forEach((neighbor) => { + const edge = graph.findEdge(vertex, neighbor); + // Find out if the distance to the neighbor is shorter in this iteration + // then in previous one. + const distanceToVertex = distances[vertex.getKey()]; + const distanceToNeighbor = distanceToVertex + edge.weight; + if (distanceToNeighbor < distances[neighbor.getKey()]) { + distances[neighbor.getKey()] = distanceToNeighbor; + previousVertices[neighbor.getKey()] = vertex; + } + }); + }); + } + + return { + distances, + previousVertices, + }; +} \ No newline at end of file