Path with smallest product of edges with weight > 0 | Javascript implementation of the approach . ; Function to return the smallest product of edges ; If the source is equal to the destination ; Initialising the array ; Bellman ford algorithm ; Loop to detect cycle ; Returning final answer ; Driver code ; Input edges ; Source and Destination ; Bellman ford
var inf = 1000000000 ; function bellman ( s , d , ed , n ) { if ( s == d ) return 0 ; var dis = Array ( n + 1 ) . fill ( inf ) ; dis [ s ] = 1 ; for ( var i = 0 ; i < n - 1 ; i ++ ) { for ( var j = 0 ; j < ed . length ; j ++ ) { dis [ ed [ j ] [ 0 ] [ 1 ] ] = Math . min ( dis [ ed [ j ] [ 0 ] [ 1 ] ] , dis [ ed [ j ] [ 0 ] [ 0 ] ] * ed [ j ] [ 1 ] ) ; } } for ( var it in ed ) { if ( dis [ it [ 0 ] [ 1 ] ] > dis [ it [ 0 ] [ 0 ] ] * it [ 1 ] ) return - 2 ; } if ( dis [ d ] == inf ) return - 1 ; else return dis [ d ] ; } var n = 3 ; var ed ; ed = [ [ [ 1 , 2 ] , 0.5 ] , [ [ 1 , 3 ] , 1.9 ] , [ [ 2 , 3 ] , 3 ] ] ; var s = 1 , d = 3 ; var get = bellman ( s , d , ed , n ) ; if ( get == - 2 ) document . write ( " " ) ; else document . write ( get ) ;