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 ; Driver code ; Given matrix ; Size of matrix ; Function call
r , c = 0 , 0 ; NEW_LINE dir = [ [ 1 , 0 ] , [ - 1 , 0 ] , [ 0 , 1 ] , [ 0 , - 1 ] , [ - 1 , - 1 ] , [ - 1 , 1 ] , [ 1 , 1 ] , [ 1 , - 1 ] ] ; NEW_LINE def valid ( i , j ) : NEW_LINE INDENT if ( i >= 0 and j >= 0 and i < r and j < c ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def find ( i , j , v ) : NEW_LINE INDENT s = 0 ; NEW_LINE for k in range ( 8 ) : NEW_LINE INDENT ni = i + dir [ k ] [ 0 ] ; NEW_LINE nj = j + dir [ k ] [ 1 ] ; NEW_LINE if ( valid ( ni , nj ) ) : NEW_LINE INDENT s += v [ ni ] [ nj ] ; NEW_LINE DEDENT DEDENT return s ; NEW_LINE DEDENT def findsumofneighbors ( M ) : NEW_LINE INDENT v = [ [ 0 for i in range ( c ) ] for j in range ( r ) ] ; NEW_LINE for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT v [ i ] [ j ] = find ( i , j , M ) ; NEW_LINE print ( v [ i ] [ j ] , end = " ▁ " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = [ [ 1 , 4 , 1 ] , [ 2 , 4 , 5 ] , [ 3 , 1 , 2 ] ] ; NEW_LINE r = len ( M [ 0 ] ) ; NEW_LINE c = len ( M [ 1 ] ) ; NEW_LINE findsumofneighbors ( M ) ; NEW_LINE DEDENT