Sum of cost of all paths to reach a given cell in a Matrix | Javascript implementation to find the sum of cost of all paths to reach ( M , N ) ; Function for computing combination ; Function to find the factorial of N ; Loop to find the factorial of a given number ; Function for coumputing the sum of all path cost ; Loop to find the contribution of each ( i , j ) in the all possible ways ; Count number of times ( i , j ) visited ; Add the contribution of grid [ i ] [ j ] in the result ; Driver Code ; Function Call
var Col = 3 ; function nCr ( n , r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } function fact ( n ) { var res = 1 ; for ( var i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } function sumPathCost ( grid , m , n ) { var sum = 0 , count ; for ( var i = 0 ; i <= m ; i ++ ) { for ( var j = 0 ; j <= n ; j ++ ) { count = nCr ( i + j , i ) * nCr ( m + n - i - j , m - i ) ; sum += count * grid [ i ] [ j ] ; } } return sum ; } var m = 2 ; var n = 2 ; var grid = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; document . write ( sumPathCost ( grid , m , n ) ) ;