Minimum odd cost path in a matrix | Javascript program to find minimum odd cost path in a matrix ; Function to find the minimum cost ; leftmost element ; rightmost element ; Any element except leftmost and rightmost element of a row is reachable from direct upper or left upper or right upper row 's block ; Counting the minimum cost ; Find the minimum cost ; Driver code
let M = 100 ; let N = 100 ; function find_min_odd_cost ( given , m , n ) { let floor = new Array ( M ) ; for ( let i = 0 ; i < M ; i ++ ) { floor [ i ] = new Array ( N ) ; for ( let j = 0 ; j < N ; j ++ ) { floor [ i ] [ j ] = 0 ; } } let min_odd_cost = 0 ; let i , j , temp ; for ( j = 0 ; j < n ; j ++ ) floor [ 0 ] [ j ] = given [ 0 ] [ j ] ; for ( i = 1 ; i < m ; i ++ ) for ( j = 0 ; j < n ; j ++ ) { if ( j == 0 ) { floor [ i ] [ j ] = given [ i ] [ j ] ; floor [ i ] [ j ] += Math . min ( floor [ i - 1 ] [ j ] , floor [ i - 1 ] [ j + 1 ] ) ; } else if ( j == n - 1 ) { floor [ i ] [ j ] = given [ i ] [ j ] ; floor [ i ] [ j ] += Math . min ( floor [ i - 1 ] [ j ] , floor [ i - 1 ] [ j - 1 ] ) ; } else { temp = Math . min ( floor [ i - 1 ] [ j ] , floor [ i - 1 ] [ j - 1 ] ) ; temp = Math . min ( temp , floor [ i - 1 ] [ j + 1 ] ) ; floor [ i ] [ j ] = given [ i ] [ j ] + temp ; } } min_odd_cost = Number . MAX_VALUE ; for ( j = 0 ; j < n ; j ++ ) { if ( floor [ n - 1 ] [ j ] % 2 == 1 ) { if ( min_odd_cost > floor [ n - 1 ] [ j ] ) min_odd_cost = floor [ n - 1 ] [ j ] ; } } if ( min_odd_cost == Number . MIN_VALUE ) return - 1 ; return min_odd_cost ; } let m = 5 , n = 5 ; let given = [ [ 1 , 2 , 3 , 4 , 6 ] , [ 1 , 2 , 3 , 4 , 5 ] , [ 1 , 2 , 3 , 4 , 5 ] , [ 1 , 2 , 3 , 4 , 5 ] , [ 100 , 2 , 3 , 4 , 5 ] ] ; document . write ( " " + find_min_odd_cost ( given , m , n ) ) ;