Minimum odd cost path in a matrix | PHP 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
< ? php $ M = 100 ; $ N = 100 ; function find_min_odd_cost ( $ given , $ m , $ n ) { global $ M , $ N ; $ floor1 [ $ M ] [ $ N ] = array ( array ( 0 ) , array ( 0 ) ) ; $ min_odd_cost = 0 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) $ floor1 [ 0 ] [ $ j ] = $ given [ 0 ] [ $ j ] ; for ( $ i = 1 ; $ i < $ m ; $ i ++ ) for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ j == 0 ) { $ floor1 [ $ i ] [ $ j ] = $ given [ $ i ] [ $ j ] ; $ floor1 [ $ i ] [ $ j ] += min ( $ floor1 [ $ i - 1 ] [ $ j ] , $ floor1 [ $ i - 1 ] [ $ j + 1 ] ) ; } else if ( $ j == $ n - 1 ) { $ floor1 [ $ i ] [ $ j ] = $ given [ $ i ] [ $ j ] ; $ floor1 [ $ i ] [ $ j ] += min ( $ floor1 [ $ i - 1 ] [ $ j ] , $ floor1 [ $ i - 1 ] [ $ j - 1 ] ) ; } else { $ temp = min ( $ floor1 [ $ i - 1 ] [ $ j ] , $ floor1 [ $ i - 1 ] [ $ j - 1 ] ) ; $ temp = min ( $ temp , $ floor1 [ $ i - 1 ] [ $ j + 1 ] ) ; $ floor1 [ $ i ] [ $ j ] = $ given [ $ i ] [ $ j ] + $ temp ; } } $ min_odd_cost = PHP_INT_MAX ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ floor1 [ $ n - 1 ] [ $ j ] % 2 == 1 ) { if ( $ min_odd_cost > $ floor1 [ $ n - 1 ] [ $ j ] ) $ min_odd_cost = $ floor1 [ $ n - 1 ] [ $ j ] ; } } if ( $ min_odd_cost == PHP_INT_MIN ) return -1 ; return $ min_odd_cost ; } $ m = 5 ; $ n = 5 ; $ given = array ( array ( 1 , 2 , 3 , 4 , 6 ) , array ( 1 , 2 , 3 , 4 , 5 ) , array ( 1 , 2 , 3 , 4 , 5 ) , array ( 1 , 2 , 3 , 4 , 5 ) , array ( 100 , 2 , 3 , 4 , 5 ) ) ; echo " Minimum ▁ odd ▁ cost ▁ is ▁ " . find_min_odd_cost ( $ given , $ m , $ n ) ; ? >