
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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