 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements
 