Maximum product of 4 adjacent elements in matrix | PHP program to find out the maximum product in the matrix which four elements are adjacent to each other in one direction ; function to find max product ; iterate the rows . ; iterate the columns . ; check the maximum product in horizontal row . ; check the maximum product in vertical row . ; check the maximum product in diagonal going through down - right ; check the maximum product in diagonal going through up - right ; Driver Code
< ? php $ n = 5 ; function FindMaxProduct ( $ arr , $ n ) { $ max = 0 ; $ result ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( ( $ j - 3 ) >= 0 ) { $ result = $ arr [ $ i ] [ $ j ] * $ arr [ $ i ] [ $ j - 1 ] * $ arr [ $ i ] [ $ j - 2 ] * $ arr [ $ i ] [ $ j - 3 ] ; if ( $ max < $ result ) $ max = $ result ; } if ( ( $ i - 3 ) >= 0 ) { $ result = $ arr [ $ i ] [ $ j ] * $ arr [ $ i - 1 ] [ $ j ] * $ arr [ $ i - 2 ] [ $ j ] * $ arr [ $ i - 3 ] [ $ j ] ; if ( $ max < $ result ) $ max = $ result ; } if ( ( $ i - 3 ) >= 0 and ( $ j - 3 ) >= 0 ) { $ result = $ arr [ $ i ] [ $ j ] * $ arr [ $ i - 1 ] [ $ j - 1 ] * $ arr [ $ i - 2 ] [ $ j - 2 ] * $ arr [ $ i - 3 ] [ $ j - 3 ] ; if ( $ max < $ result ) $ max = $ result ; } if ( ( $ i - 3 ) >= 0 and ( $ j - 1 ) <= 0 ) { $ result = $ arr [ $ i ] [ $ j ] * $ arr [ $ i - 1 ] [ $ j + 1 ] * $ arr [ $ i - 2 ] [ $ j + 2 ] * $ arr [ $ i - 3 ] [ $ j + 3 ] ; if ( $ max < $ result ) $ max = $ result ; } } } return $ max ; } $ arr = array ( array ( 1 , 2 , 3 , 4 , 5 ) , array ( 6 , 7 , 8 , 9 , 1 ) , array ( 2 , 3 , 4 , 5 , 6 ) , array ( 7 , 8 , 9 , 1 , 0 ) , array ( 9 , 6 , 4 , 2 , 3 ) ) ; echo FindMaxProduct ( $ arr , $ n ) ; ? >