Created
March 15, 2015 10:33
-
-
Save nicoptere/8f9dc0eac352444d4714 to your computer and use it in GitHub Desktop.
dijkstra algorithm ( brutal implementation )
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
function dijkstra( graph_array, source, target) | |
{ | |
//builds adjacency list | |
var vertices = []; | |
var neighbours = {}; | |
graph_array.forEach( function( edge ) | |
{ | |
//store the vertex 0 | |
if( vertices.indexOf( edge[0] ) == -1 )vertices.push( edge[0] ); | |
//creates the adjacency map for this vertex | |
if( neighbours[edge[0]] == null )neighbours[edge[0]] = []; | |
//stores the other vertex of this edges in the adjacency map | |
neighbours[edge[0]].push( { end: edge[1], cost: edge[2]} ); | |
//same for the other vertex of this edge | |
if( vertices.indexOf( edge[1] ) == -1 )vertices.push( edge[1] ); | |
if( neighbours[edge[1]] == null )neighbours[edge[1]] = []; | |
neighbours[edge[1]].push( { end: edge[0], cost: edge[2]} ); | |
}); | |
//creates a distance dictionary & an linked list (to store the shortest path ) | |
var dist = {}; | |
var previous = {}; | |
//& initializes them with default values | |
vertices.forEach( function( vertex) | |
{ | |
dist[ vertex ] = Number.POSITIVE_INFINITY; | |
previous[vertex] = null; | |
} ); | |
//initializes the distance to source at 0 | |
dist[source] = 0; | |
var queue = vertices; | |
while( queue.length > 0 ) | |
{ | |
//select the closest vertex | |
min = Number.POSITIVE_INFINITY; | |
queue.forEach( function(vertex) | |
{ | |
if (dist[vertex] < min) | |
{ | |
min = dist[ vertex ]; | |
u = vertex; | |
} | |
}); | |
//removes current node from the queue | |
queue.splice( queue.indexOf( u ), 1 ); | |
if( dist[ u ] == Number.POSITIVE_INFINITY || u == target ) | |
{ | |
break; | |
} | |
//for all neighbours of U, update distance to target node | |
if( neighbours[ u ] != null ) | |
{ | |
neighbours[ u ].forEach( | |
function(arr) | |
{ | |
var alt = dist[u] + arr[ "cost" ]; | |
if( alt < dist[ arr[ "end" ] ] ) | |
{ | |
dist[ arr[ "end" ] ] = alt; | |
previous[ arr[ "end" ]] = u; | |
} | |
}); | |
} | |
} | |
//compute shortest path | |
var solution = []; | |
while( previous[ target ] != null ) | |
{ | |
solution.unshift( target ); | |
target = previous[ target ]; | |
} | |
solution.unshift( target ); | |
return solution; | |
} | |
graph_array = [ | |
["a", "b", 7], | |
["a", "c", 9], | |
["a", "f", 14], | |
["b", "c", 10], | |
["b", "d", 15], | |
["c", "d", 11], | |
["c", "f", 2], | |
["d", "e", 6], | |
["e", "f", 9 ] | |
]; | |
var path = dijkstra(graph_array, "a", "e" ); | |
//should log : a,c,f,e | |
console.log( "path is a->e: " + path ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment