Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix | Java program for the above approach ; 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 ; Driver code ; Given matrix ; Size of matrix ; Function call
import java . util . * ; import java . lang . * ; public class GFG { private static int r , c ; static int [ ] [ ] dir = { { 1 , 0 } , { - 1 , 0 } , { 0 , 1 } , { 0 , - 1 } , { - 1 , - 1 } , { - 1 , 1 } , { 1 , 1 } , { 1 , - 1 } } ; public static boolean valid ( int i , int j ) { if ( i >= 0 && j >= 0 && i < r && j < c ) return true ; return false ; } static int find ( int i , int j , int [ ] [ ] v ) { int s = 0 ; for ( int k = 0 ; k < 8 ; k ++ ) { int ni = i + dir [ k ] [ 0 ] , nj = j + dir [ k ] [ 1 ] ; if ( valid ( ni , nj ) ) s += v [ ni ] [ nj ] ; } return s ; } static void findsumofneighbors ( int [ ] [ ] M ) { int [ ] [ ] v = new int [ r ] ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { v [ i ] [ j ] = find ( i , j , M ) ; System . out . print ( v [ i ] [ j ] + " ▁ " ) ; } System . out . println ( " " ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] M = { { 1 , 4 , 1 } , { 2 , 4 , 5 } , { 3 , 1 , 2 } } ; r = M . length ; c = M [ 0 ] . length ; findsumofneighbors ( M ) ; } }