Created
March 8, 2025 21:36
-
-
Save migtibincoski/4a93a5625cee7447975efb81d27d6d80 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function dijkstra(graph, start) { | |
const queue = [[0, start]]; | |
const shortestPaths = {}; | |
for (const vertex in graph) { | |
shortestPaths[vertex] = Infinity; | |
} | |
shortestPaths[start] = 0; | |
while (queue.length > 0) { | |
queue.sort((a, b) => a[0] - b[0]); | |
const [currentCost, currentVertex] = queue.shift(); | |
for (const neighbor in graph[currentVertex]) { | |
const weight = graph[currentVertex][neighbor]; | |
const cost = currentCost + weight; | |
if (cost < shortestPaths[neighbor]) { | |
shortestPaths[neighbor] = cost; | |
queue.push([cost, neighbor]); | |
} | |
} | |
} | |
return shortestPaths; | |
} | |
const graph = { | |
'A': {'B': 1, 'C': 4}, | |
'B': {'A': 1, 'C': 2, 'D': 5}, | |
'C': {'A': 4, 'B': 2, 'D': 1}, | |
'D': {'B': 5, 'C': 1} | |
}; | |
const shortestPaths = dijkstra(graph, 'A'); | |
console.log(`Shortest paths from 'A':`, shortestPaths); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment