Created
March 10, 2019 17:58
-
-
Save dbalduini/542ea7ac431d9b5c669a36ac014a5177 to your computer and use it in GitHub Desktop.
JS BinDijkstra algorithm// source https://jsbin.com/nigedok
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
// dijkstra algorithm | |
// Dijkstra’s algorithm works when all the weights are positive | |
// If you have negative weights, use the Bellman-Ford algorithm. | |
// START -> A | |
// START -> B | |
// B -> A | |
// A -> FIN | |
// B -> FIN | |
var graph = {} | |
graph.start = {} | |
graph.start.a = 6 | |
graph.start.b = 2 | |
graph.a = {} | |
graph.a.fin = 1 | |
graph.b = {} | |
graph.b.a = 3 | |
graph.b.fin = 5 | |
graph.fin = {} | |
// how long it takes to get to the node from the start | |
var costs = {} | |
costs.a = 6 | |
costs.b = 2 | |
costs.fin = Infinity | |
// parents dict so we can build the shortest path | |
var parents = {} | |
parents.a = 'start' | |
parents.b = 'start' | |
parents.fin = null | |
// track visited nodes | |
var visited = [] | |
function findLowestCostNode(costs) { | |
var lowestNode; | |
var lowestCost = Infinity; | |
Object.keys(costs).forEach(function (node) { | |
if (visited.indexOf(node) === -1 && costs[node] < lowestCost) { | |
lowestNode = node | |
lowestCost = costs[node] | |
} | |
}); | |
return lowestNode; | |
} | |
function dijkstra(graph) { | |
var node = findLowestCostNode(costs) | |
while (node) { | |
// cost of x | |
var cost = costs[node] | |
var neighbors = graph[node] | |
// update neighbors costs | |
Object.keys(neighbors).forEach(function (n) { | |
// distance from x to n | |
var ncost = neighbors[n] | |
// distance from the start passing through x to n | |
var newCost = cost + ncost | |
// save this shorter path by updating the parent and how long it cost | |
if (costs[n] > newCost) { | |
costs[n] = newCost | |
parents[n] = node | |
} | |
}); | |
visited.push(node) | |
node = findLowestCostNode(costs) | |
} | |
} | |
function shortestPath(parents) { | |
var path = [] | |
// start in the target node | |
var node = 'fin' | |
while(node) { | |
path.unshift(node) | |
node = parents[node]; | |
} | |
return path; | |
} | |
dijkstra(graph); | |
console.log(shortestPath(parents)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment