11var D ; // D[i] indicates whether the i-th node is discovered or not
2+ var W ; // W[i] indicates the weight of the i-th node
23
3- function DFS ( v , p ) { // v = current node, p = previous node
4- tracer . visit ( v , p ) ;
5- D [ v ] = true ; // label v as discovered
6- G [ v ] . forEach ( function ( w ) { // G[v] contains edges starting from v
7- if ( ! D [ w ] ) { // if w is not labeled as discovered
8- DFS ( w , v ) ; // recursively call DFS
4+ function getWeight ( v , p ) {
5+ if ( p === undefined ) return 0 ;
6+ return W [ p ] + G [ p ] [ v ] ; // the sum of the weights of previous node and the path
7+ }
8+
9+ function DFS ( node , parent ) { // node = current node, parent = previous node
10+ D [ node ] = true ; // label current node as discovered
11+ W [ node ] = getWeight ( node , parent ) ; // update the weight of the node
12+ tracer . _visit ( node , parent , W [ node ] ) ;
13+ for ( var i = 0 ; i < G [ node ] . length ; i ++ ) {
14+ if ( G [ node ] [ i ] ) { // if the path from current node to the i-th node exists
15+ if ( ! D [ i ] ) { // if the i-th node is not labeled as discovered
16+ DFS ( i , node ) ; // recursively call DFS
17+ }
918 }
10- } ) ;
11- tracer . leave ( v , p ) ;
19+ }
20+ D [ node ] = false ; // label current node as undiscovered
21+ W [ node ] = 0 ; // reset the weight of the node
22+ tracer . _leave ( node , parent , W [ node ] ) ;
1223}
1324
25+ tracer . _pace ( 1000 ) ;
1426for ( var i = 0 ; i < G . length ; i ++ ) { // start from every node
15- tracer . print ( 'start from ' + i ) ;
16- D = new Array ( G . length ) ;
27+ tracer . _print ( 'start from ' + i ) ;
28+ D = [ ] ;
29+ W = [ ] ;
30+ for ( var j = 0 ; j < G . length ; j ++ ) {
31+ D [ j ] = false ;
32+ W [ j ] = 0 ;
33+ }
1734 DFS ( i ) ;
18- tracer . clear ( ) ;
35+ tracer . _clear ( ) ;
1936}
0 commit comments