|
| 1 | +/** |
| 2 | + * Author: Samarth Jain |
| 3 | + * Dijkstra's Algorithm implementation in JavaScript |
| 4 | + * Dijkstra's Algorithm calculates the minimum distance between two nodes. |
| 5 | + * It is used to find the shortes path. |
| 6 | + * It uses graph data structure. |
| 7 | + */ |
| 8 | + |
| 9 | +function createGraph (V, E) { |
| 10 | + // V - Number of vertices in graph |
| 11 | + // E - Number of edges in graph (u,v,w) |
| 12 | + const adjList = [] // Adjacency list |
| 13 | + for (let i = 0; i < V; i++) { |
| 14 | + adjList.push([]) |
| 15 | + } |
| 16 | + for (let i = 0; i < E.length; i++) { |
| 17 | + adjList[E[i][0]].push([E[i][1], E[i][2]]) |
| 18 | + adjList[E[i][1]].push([E[i][0], E[i][2]]) |
| 19 | + } |
| 20 | + return adjList |
| 21 | +} |
| 22 | + |
| 23 | +function djikstra (graph, V, src) { |
| 24 | + const vis = Array(V).fill(0) |
| 25 | + const dist = [] |
| 26 | + for (let i = 0; i < V; i++) dist.push([10000, -1]) |
| 27 | + dist[src][0] = 0 |
| 28 | + |
| 29 | + for (let i = 0; i < V - 1; i++) { |
| 30 | + let mn = -1 |
| 31 | + for (let j = 0; j < V; j++) { |
| 32 | + if (vis[j] === 0) { |
| 33 | + if (mn === -1 || dist[j][0] < dist[mn][0]) mn = j |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + vis[mn] = 1 |
| 38 | + for (let j = 0; j < graph[mn].length; j++) { |
| 39 | + const edge = graph[mn][j] |
| 40 | + if (vis[edge[0]] === 0 && dist[edge[0]][0] > dist[mn][0] + edge[1]) { |
| 41 | + dist[edge[0]][0] = dist[mn][0] + edge[1] |
| 42 | + dist[edge[0]][1] = mn |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return dist |
| 48 | +} |
| 49 | + |
| 50 | +const V = 9 |
| 51 | +const E = [ |
| 52 | + [0, 1, 4], |
| 53 | + [0, 7, 8], |
| 54 | + [1, 7, 11], |
| 55 | + [1, 2, 8], |
| 56 | + [7, 8, 7], |
| 57 | + [6, 7, 1], |
| 58 | + [2, 8, 2], |
| 59 | + [6, 8, 6], |
| 60 | + [5, 6, 2], |
| 61 | + [2, 5, 4], |
| 62 | + [2, 3, 7], |
| 63 | + [3, 5, 14], |
| 64 | + [3, 4, 9], |
| 65 | + [4, 5, 10] |
| 66 | +] |
| 67 | + |
| 68 | +const graph = createGraph(V, E) |
| 69 | +const distances = djikstra(graph, V, 0) |
| 70 | + |
| 71 | +/** |
| 72 | + * The first value in the array determines the minimum distance and the |
| 73 | + * second value represents the parent node from which the minimum distance has been calculated |
| 74 | + */ |
| 75 | + |
| 76 | +console.log(distances) |
0 commit comments