Skip to content

Commit 2982ae9

Browse files
committed
Dijkstra's shortest path algorithm using min heap as priority queue
1 parent 7ac6857 commit 2982ae9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

19-Dijkstras-Shortest-Path-Algorithm/02-dijkstra-heap-priority-queue.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,37 @@
1+
/**
2+
* Dijkstra's Shortest Path Algorithm
3+
* Dijkstra's algorithm is greedy! That can cause problems!
4+
*
5+
*
6+
* Time Complexity: Time Complexity of Dijkstra's Algorithm is O ( V 2 )
7+
* but with min-priority queue it drops down to O ( V + E log V )
8+
*
9+
* @author Aditya Hajare <https://github.com/aditya43>
10+
*
11+
* IMPORTANT POINTS AND PSUDOCODE
12+
* -----------------------------------
13+
* 1. This function should accept a starting and ending vertex
14+
* 2. Create an object (we'll call it distances) and set each key to be every
15+
* vertex in the adjacency list with a value of infinity, except for the
16+
* starting vertex which should have a value of 0.
17+
* 3. After setting a value in the distances object, add each vertex with
18+
* a priority of Infinity to the priority queue, except the starting vertex,
19+
* which should have a priority of 0 because that's where we begin.
20+
* 4. Create another object called previous and set each key to be every
21+
* vertex in the adjacency list with a value of null
22+
* 5. Start looping as long as there is anything in the priority queue
23+
* - dequeue a vertex from the priority queue
24+
* - If that vertex is the same as the ending vertex - we are done!
25+
* - Otherwise loop through each value in the adjacency list at that vertex
26+
* - Calculate the distance to that vertex from the starting vertex
27+
* - if the distance is less than what is currently stored in our
28+
* distances object
29+
* - update the distances object with new lower distance
30+
* - update the previous object to contain that vertex
31+
* - enqueue the vertex with the total distance from the start node
32+
*
33+
* We can improve this algorithm by adding a heuristics (a best guess)
34+
*/
135
class Vertex {
236
constructor (vertex, weight) {
337
this.node = vertex;

0 commit comments

Comments
 (0)