11function Dijkstra ( start , end ) {
2- tracer . _sleep ( 333 ) ;
2+ tracer . _sleep ( ) ;
33 var MAX_VALUE = Infinity ;
44 var minIndex , minDistance ;
55 var S = [ ] ; // S[i] returns the distance from node v to node start
@@ -9,7 +9,8 @@ function Dijkstra(start, end) {
99 S [ i ] = MAX_VALUE ;
1010 }
1111 S [ start ] = 0 ; // Starting node is at distance 0 from itself
12- for ( var k = 0 ; k < G . length ; k ++ ) {
12+ var k = G . length ;
13+ while ( k -- ) {
1314 // Finding a node with the shortest distance from S[minIndex]
1415 minDistance = MAX_VALUE ;
1516 for ( i = 0 ; i < G . length ; i ++ ) {
@@ -18,33 +19,32 @@ function Dijkstra(start, end) {
1819 minIndex = i ;
1920 }
2021 }
21- tracer . _visit ( minIndex , undefined ) ;
22- tracer . _sleep ( 500 ) ;
22+ if ( minDistance == MAX_VALUE ) break ; // If there is no edge from current node, jump out of loop
2323 D [ minIndex ] = true ;
24- if ( minDistance == MAX_VALUE ) { // If the distance is infinity, there is no more paths
25- tracer . _print ( 'there is no path from ' + s + ' to ' + e ) ;
26- return false ;
27- }
24+ tracer . _visit ( minIndex ) ;
2825 // For every unvisited neighbour of current node, we check
2926 // whether the path to it is shorter if going over the current node
3027 for ( i = 0 ; i < G . length ; i ++ ) {
31- if ( G [ minIndex ] [ i ] && ! D [ i ] && ( S [ i ] > S [ minIndex ] + G [ minIndex ] [ i ] ) ) {
28+ if ( G [ minIndex ] [ i ] && S [ i ] > S [ minIndex ] + G [ minIndex ] [ i ] ) {
3229 S [ i ] = S [ minIndex ] + G [ minIndex ] [ i ] ;
3330 tracer . _visit ( i , minIndex , S [ i ] ) ;
34- tracer . _sleep ( 500 ) ;
3531 tracer . _leave ( i , minIndex , S [ i ] ) ;
3632 }
3733 }
38- tracer . _leave ( minIndex , undefined ) ;
34+ tracer . _leave ( minIndex ) ;
35+ }
36+ if ( S [ end ] == MAX_VALUE ) {
37+ tracer . _print ( 'there is no path from ' + start + ' to ' + end ) ;
38+ } else {
39+ tracer . _print ( 'the shortest path from ' + start + ' to ' + end + ' is ' + S [ end ] ) ;
3940 }
40- tracer . _print ( 'the shortest path from ' + s + ' to ' + e + ' is ' + S [ e ] ) ;
4141}
4242
4343var s = Math . random ( ) * G . length | 0 ; // s = start node
4444var e ; // e = end node
4545do {
4646 e = Math . random ( ) * G . length | 0 ;
4747} while ( s == e ) ;
48- tracer . _pace ( 100 ) ;
48+ tracer . _pace ( 500 ) ;
4949tracer . _print ( 'finding the shortest path from ' + s + ' to ' + e ) ;
5050Dijkstra ( s , e ) ;
0 commit comments