Skip to content

Instantly share code, notes, and snippets.

@mgechev
Created November 3, 2014 09:27
Show Gist options
  • Save mgechev/562548870ef3b4ad16c6 to your computer and use it in GitHub Desktop.
Save mgechev/562548870ef3b4ad16c6 to your computer and use it in GitHub Desktop.
Dijkstra's shortest path algorithm
/*
graph[i][j] indicates the distance between vertex i and vertex j
basically a single entry in this matrix is an edge in the graph.
When graph[i][j] is Infinity, this means that there is no edge between
vertexes i and j.
*/
var graph = [[0, 1, Infinity, 6, Infinity, 7, Infinity],
[1, 0, 5, 12, Infinity, 8, Infinity],
[Infinity, 5, 0, 2, 4, Infinity, Infinity],
[6, 12, 2, 0, Infinity, 9, 10],
[Infinity, Infinity, 4, 0, Infinity, 11],
[7, 8, Infinity, 9, Infinity, 0, 3],
[Infinity, Infinity, Infinity, 10, 11, 3]];
// Finds the minimum distance between two nodes
function shortestPath(start, dest, graph) {
'use strict';
var current = start,
queue = [],
path = [],
currentDistance = 0,
visited = [];
for (var i = 0; i < graph.length; i += 1) {
queue[i] = Infinity;
visited[i] = false;
}
queue[start] = 0;
do {
path.push(current);
visited[current] = true;
for (i = 0; i < graph.length; i += 1) {
if (currentDistance + graph[current][i] < queue[i]) {
queue[i] = currentDistance + graph[current][i];
}
}
// Could be optimized using fibonacci heap data structure
var minDistance = Infinity;
current = -1;
for (i = 0; i < graph.length; i += 1) {
if (queue[i] < minDistance && !visited[i]) {
current = i;
minDistance = queue[i];
}
}
currentDistance = minDistance;
} while (current !== dest && current !== -1);
if (current !== dest && current !== -1) {
return Infinity;
}
return currentDistance;
}
// Sample call
shortestPath(0, 5, graph);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment