|
| 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 | + */ |
1 | 35 | class Vertex {
|
2 | 36 | constructor (vertex, weight) {
|
3 | 37 | this.node = vertex;
|
|
0 commit comments