Maximum product of 4 adjacent elements in matrix | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 5 ; int FindMaxProduct ( int arr [ ] [ n ] , int n ) { int max = 0 , result ; for ( int i = 0 ; i < n ; i ++ ) { for ( int 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 && ( 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 && ( 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 ; } int main ( ) { int arr [ ] [ 5 ] = { { 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 } } ; cout << FindMaxProduct ( arr , n ) ; return 0 ; }