- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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(", ")+ "\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.

- Related Questions & Answers
- Shortest Path algorithm in Computer Network
- Shortest Path in Binary Matrix in C++
- Shortest path with exactly k Edges
- Dijkstra’s Shortest Path Algorithm
- Shortest Path in a Directed Acyclic Graph
- Shortest Path with Alternating Colors in Python
- Shortest Path Visiting All Nodes in C++
- Shortest Path to Get All Keys in C++
- What is the Shortest Path Routing in Computer Network?
- Shortest Path in a Grid with Obstacles Elimination in C++
- C++ Program for Dijkstra’s shortest path algorithm?
- Yen's k-Shortest Path Algorithm in Data Structure
- Find shortest safe route in a path with landmines in C++
- C / C++ Program for Dijkstra's shortest path algorithm
- Print shortest path to print a string on screen in C Program.

Advertisements