Last active
December 30, 2023 03:18
-
-
Save primaryobjects/c23c022d80e0b65e101905c9bb2c1ac7 to your computer and use it in GitHub Desktop.
Dijkstra's Algorithm https://neetcode.io/problems/dijkstra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* const PriorityQueue = require('priority-queue-js'); | |
*/ | |
class Solution { | |
/** | |
* @param {number} n | |
* @param {number[][]} edges | |
* @param {number} src | |
* @returns {Object} | |
*/ | |
shortestPath(n, edges, src) { | |
const results = {}; | |
// Initialize an empty adjacency matrix | |
var graph = []; | |
for (var i = 0; i < n; i++) { | |
graph[i] = []; | |
for (var j = 0; j < n; j++) { | |
graph[i][j] = i === j ? 0 : Infinity; | |
} | |
} | |
// Populate the adjacency matrix using the edges | |
for (var i = 0; i < edges.length; i++) { | |
var u = edges[i][0]; | |
var v = edges[i][1]; | |
var w = edges[i][2]; | |
graph[u][v] = w; | |
//graph[v][u] = w; // Remove this line if the graph is directed | |
} | |
const distances = this.dijkstra(graph, src); | |
for (let i=0; i<n; i++) { | |
results[i] = distances[i] === Number.MAX_VALUE ? -1 : distances[i]; | |
} | |
return results; | |
} | |
dijkstra(graph, start) { | |
var distances = []; | |
for (var i = 0; i < graph.length; i++) distances[i] = Number.MAX_VALUE; | |
distances[start] = 0; | |
var visited = []; | |
while (true) { | |
var shortestDistance = Number.MAX_VALUE; | |
var shortestIndex = -1; | |
for (var i = 0; i < graph.length; i++) { | |
if (distances[i] < shortestDistance && !visited[i]) { | |
shortestDistance = distances[i]; | |
shortestIndex = i; | |
} | |
} | |
if (shortestIndex === -1) { | |
return distances; | |
} | |
for (var i = 0; i < graph[shortestIndex].length; i++) { | |
if (graph[shortestIndex][i] !== 0 && distances[i] > distances[shortestIndex] + graph[shortestIndex][i]) { | |
distances[i] = distances[shortestIndex] + graph[shortestIndex][i]; | |
} | |
} | |
visited[shortestIndex] = true; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
n = 5 | |
edges = [[0,1,10], [0,2,3], [1,3,2], [2,1,4], [2,3,8], [2,4,2], [3,4,5]] | |
src = 0 | |
s = new Solution(); | |
const result = s.shortestPath(n, edges, src); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment