Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int r , c ; vector < vector < int > > dir = { { 1 , 0 } , { -1 , 0 } , { 0 , 1 } , { 0 , -1 } , { -1 , -1 } , { -1 , 1 } , { 1 , 1 } , { 1 , -1 } } ; bool valid ( int i , int j ) { if ( i >= 0 && j >= 0 && i < r && j < c ) return 1 ; return 0 ; } int find ( int i , int j , vector < vector < int > > & v ) { int s = 0 ; for ( auto x : dir ) { int ni = i + x [ 0 ] , nj = j + x [ 1 ] ; if ( valid ( ni , nj ) ) s += v [ ni ] [ nj ] ; } return s ; } void findsumofneighbors ( vector < vector < int > > & M ) { vector < vector < int > > v ( r , vector < int > ( c , 0 ) ) ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { v [ i ] [ j ] = find ( i , j , M ) ; cout << v [ i ] [ j ] << " ▁ " ; } cout << " STRNEWLINE " ; } } int main ( ) { vector < vector < int > > M = { { 1 , 4 , 1 } , { 2 , 4 , 5 } , { 3 , 1 , 2 } } ; r = M . size ( ) , c = M [ 0 ] . size ( ) ; findsumofneighbors ( M ) ; }