1
1
function Dijkstra ( start , end ) {
2
- tracer . _sleep ( 333 ) ;
2
+ tracer . _sleep ( ) ;
3
3
var MAX_VALUE = Infinity ;
4
4
var minIndex , minDistance ;
5
5
var S = [ ] ; // S[i] returns the distance from node v to node start
@@ -9,7 +9,8 @@ function Dijkstra(start, end) {
9
9
S [ i ] = MAX_VALUE ;
10
10
}
11
11
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 -- ) {
13
14
// Finding a node with the shortest distance from S[minIndex]
14
15
minDistance = MAX_VALUE ;
15
16
for ( i = 0 ; i < G . length ; i ++ ) {
@@ -18,33 +19,32 @@ function Dijkstra(start, end) {
18
19
minIndex = i ;
19
20
}
20
21
}
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
23
23
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 ) ;
28
25
// For every unvisited neighbour of current node, we check
29
26
// whether the path to it is shorter if going over the current node
30
27
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 ] ) {
32
29
S [ i ] = S [ minIndex ] + G [ minIndex ] [ i ] ;
33
30
tracer . _visit ( i , minIndex , S [ i ] ) ;
34
- tracer . _sleep ( 500 ) ;
35
31
tracer . _leave ( i , minIndex , S [ i ] ) ;
36
32
}
37
33
}
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 ] ) ;
39
40
}
40
- tracer . _print ( 'the shortest path from ' + s + ' to ' + e + ' is ' + S [ e ] ) ;
41
41
}
42
42
43
43
var s = Math . random ( ) * G . length | 0 ; // s = start node
44
44
var e ; // e = end node
45
45
do {
46
46
e = Math . random ( ) * G . length | 0 ;
47
47
} while ( s == e ) ;
48
- tracer . _pace ( 100 ) ;
48
+ tracer . _pace ( 500 ) ;
49
49
tracer . _print ( 'finding the shortest path from ' + s + ' to ' + e ) ;
50
50
Dijkstra ( s , e ) ;
0 commit comments