Skip to content

Instantly share code, notes, and snippets.

@zerbitx
Created July 7, 2014 02:15
Show Gist options
  • Save zerbitx/18af45cb9c98d5e896f4 to your computer and use it in GitHub Desktop.
Save zerbitx/18af45cb9c98d5e896f4 to your computer and use it in GitHub Desktop.
Dijkstra's in JavaScript (requires underscore)
var _ = require('underscore');
function PriorityQueue()
{
!function(pq){
var nodes = [];
function comp(a,b) {
return a.priority - b.priority;
}
pq.isNotEmpty = function() {
return nodes.length;
}
pq.enqueue = function(v,priority)
{
nodes.push({key: v, priority: priority});
nodes.sort(comp);
};
pq.extractMin = function(){
var min = nodes.shift();
return min.key;
};
pq.decreaseKey = function(v,priority){
_.each(nodes,function(n){
if(n.key === v)
{
n.priority = priority;
return false;
} else {
return true
}
});
nodes.sort(comp);
}
}(this);
}
function Dijkstra(start,graph)
{
var pq = new PriorityQueue(),
dist = {},
prev = {};
_.each(graph,function(_,v){
dist[v] = Infinity;
prev[v] = null;
});
dist[start] = 0;
_.each(graph,function(edge,v){
pq.enqueue(v, (v === start) ? 0 : Infinity);
});
while(pq.isNotEmpty())
{
var u = pq.extractMin();
_.each(graph[u],function(edge,v){
if(dist[v] > dist[u] + edge)
{
dist[v] = dist[u] + edge;
prev[v] = u;
pq.decreaseKey(v,edge);
}
});
}
return [dist,prev];
}
var first_graph = {
'A':{'B':4,'C':2},
'B':{'C':3,'D':2,'E':3},
'C':{'B':1,'D':4,'E':5},
'D':{},
'E':{'D':1}
};
var second_graph = {
'A': {B: 7, C: 8},
'B': {A: 7, F: 2},
'C': {A: 8, F: 6, G: 4},
'D': {F: 8},
'E': {H: 1},
'F': {B: 2, C: 6, D: 8, G: 9, H: 3},
'G': {C: 4, F: 9},
'H': {E: 1, F: 3}
};
var first_path = Dijkstra('A',first_graph);
var second_path = Dijkstra('A',second_graph);
console.log(first_path);
console.log(second_path);
@mmontag
Copy link

mmontag commented Oct 12, 2018

Note:
This is a naive PriorityQueue implementation giving O(n log n) runtime for enqueue and decreaseKey.
Heap based implementations are O(log n).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment