Shortest path algorithms in Javascript


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(", ")+ "
";    });    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.

Updated on: 15-Jun-2020

801 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements