Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix | Initialize rows and columns ; Store all 8 directions ; Function to check if a cell ( i , j ) is valid or not ; Function to find sum of adjacent cells for cell ( i , j ) ; Initialize sum ; Visit all 8 directions ; Check if cell is valid ; Return sum ; Function to print sum of adjacent elements ; Stores the resultant matrix ; Iterate each elements of matrix ; Find adjacent sum ; Given matrix ; Size of matrix ; Function call
let r , c ; let dir = [ [ 1 , 0 ] , [ - 1 , 0 ] , [ 0 , 1 ] , [ 0 , - 1 ] , [ - 1 , - 1 ] , [ - 1 , 1 ] , [ 1 , 1 ] , [ 1 , - 1 ] ] ; function valid ( i , j ) { if ( i >= 0 && j >= 0 && i < r && j < c ) return true ; return false ; } function find ( i , j , v ) { let s = 0 ; for ( let k = 0 ; k < 8 ; k ++ ) { let ni = i + dir [ k ] [ 0 ] , nj = j + dir [ k ] [ 1 ] ; if ( valid ( ni , nj ) ) s += v [ ni ] [ nj ] ; } return s ; } function findsumofneighbors ( M ) { let v = new Array ( r ) ; for ( var i = 0 ; i < v . length ; i ++ ) { v [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < r ; i ++ ) { for ( let j = 0 ; j < c ; j ++ ) { v [ i ] [ j ] = find ( i , j , M ) ; document . write ( v [ i ] [ j ] + " " ) ; } document . write ( " " ) ; } } let M = [ [ 1 , 4 , 1 ] , [ 2 , 4 , 5 ] , [ 3 , 1 , 2 ] ] ; r = M . length ; c = M [ 0 ] . length ; findsumofneighbors ( M ) ;