Find the count of mountains in a given Matrix | Function to count number of mountains in a given matrix of size n ; form another matrix with one extra layer of border elements . Border elements will contain INT_MIN value . ; For border elements , set value as INT_MIN ; For rest elements , just copy it into new matrix ; Check for mountains in the modified matrix ; check for all directions ; Driver code
function countMountains ( a , n ) { var A = new Array ( n + 2 ) . fill ( 0 ) . map ( ( ) => new Array ( n + 2 ) . fill ( 0 ) ) ; var count = 0 ; for ( var i = 0 ; i < n + 2 ; i ++ ) { for ( var j = 0 ; j < n + 2 ; j ++ ) { if ( ( i == 0 ) || ( j == 0 ) || ( i == n + 1 ) || ( j == n + 1 ) ) { A [ i ] [ j ] = Number . MIN_VALUE ; } else { A [ i ] [ j ] = a [ i - 1 ] [ j - 1 ] ; } } } for ( var i = 1 ; i <= n ; i ++ ) { for ( var j = 1 ; j <= n ; j ++ ) { if ( ( A [ i ] [ j ] > A [ i - 1 ] [ j ] ) && ( A [ i ] [ j ] > A [ i + 1 ] [ j ] ) && ( A [ i ] [ j ] > A [ i ] [ j - 1 ] ) && ( A [ i ] [ j ] > A [ i ] [ j + 1 ] ) && ( A [ i ] [ j ] > A [ i - 1 ] [ j - 1 ] ) && ( A [ i ] [ j ] > A [ i + 1 ] [ j + 1 ] ) && ( A [ i ] [ j ] > A [ i - 1 ] [ j + 1 ] ) && ( A [ i ] [ j ] > A [ i + 1 ] [ j - 1 ] ) ) { count ++ ; } } } return count ; } var a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; var n = 3 ; document . write ( countMountains ( a , n ) ) ;