Shortest path algorithms in Javascript

Front End TechnologyWeb DevelopmentJavascript

In graph theory, the shortest path problem is the problem of finding a path between two vertices (or nodes) in a graph such that the sum of the weights of its constituent edges is minimized. Here we need to modify our add edge and add directed methods to allow adding weights to the edges as well. 

Let us look at how we can add this −

Example

/**
   * Adds 2 edges with the same weight in either direction
   *
   *             weight
   * node1 <================> node2
   *             weight
   *
*/
addEdge(node1, node2, weight = 1) {
   this.edges[node1].push({ node: node2, weight: weight });
   this.edges[node2].push({ node: node1, weight: weight });
}

/**
   *  Add the following edge:
   *
   *             weight
   * node1 ----------------> node2
   *
*/

addDirectedEdge(node1, node2, weight = 1) {
   this.edges[node1].push({ node: node2, weight: weight });
}

display() {
   let graph = "";
   this.nodes.forEach(node => {
      graph += node + "->" + this.edges[node].map(n => n.node) .join(", ")+ "\n";
   });
   console.log(graph);
}

Now when adding an edge to our graph, if we don't specify a weight, a default weight of 1 is assigned to that edge. We can now use this to implement shortest path algorithms.

raja
Published on 28-Jun-2018 14:43:11
Advertisements