Maximum product of 4 adjacent elements in matrix | Python3 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
n = 5 NEW_LINE def FindMaxProduct ( arr , n ) : NEW_LINE INDENT max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( j - 3 ) >= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i ] [ j - 1 ] * arr [ i ] [ j - 2 ] * arr [ i ] [ j - 3 ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT if ( ( i - 3 ) >= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i - 1 ] [ j ] * arr [ i - 2 ] [ j ] * arr [ i - 3 ] [ j ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT if ( ( i - 3 ) >= 0 and ( j - 3 ) >= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i - 1 ] [ j - 1 ] * arr [ i - 2 ] [ j - 2 ] * arr [ i - 3 ] [ j - 3 ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT if ( ( i - 3 ) >= 0 and ( j - 1 ) <= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i - 1 ] [ j + 1 ] * arr [ i - 2 ] [ j + 2 ] * arr [ i - 3 ] [ j + 3 ] ) NEW_LINE if ( max < result ) : NEW_LINE INDENT max = result NEW_LINE DEDENT DEDENT DEDENT DEDENT return max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 1 ] , [ 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 1 , 0 ] , [ 9 , 6 , 4 , 2 , 3 ] ] NEW_LINE print ( FindMaxProduct ( arr , n ) ) NEW_LINE DEDENT