Okay, so to make it easy, just distinguish that there are three cases for EACH SYMETRIC matrix:
- Element is the corner - it has 3 neighbours
- Element is part of the edge, but not the corner - it has 5 neighbours
- Element is neither corner or edge - it has 8 neighours
There are also 4 possible corners and 4 possible eges for all 2D matrixes.(Excluding those with 1 column, row, which I would call vectors)
Pseudocode:(We assume proper matrix with equal numbers of elements in rows and columns)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
rows=len(matrix)
cols=len(matrix[0])
sumation=0
for i in range(len(matrix)):
doesleftexist=1
doestopexist=1
doesbottomexist=1
doesrightexist=1
for j in range(len(matrix[0])):
if(i==0): #element to the top doesn't exist
doesleftexist=0
if(j==0): #element to the left doesn't exist
doestopexist=0
if(i==rows-1) #element to the bottom doesn't exist
doesbottomexist=0
if(j==cols-1) #element to the right doesn't exist
doesrightexist=0
if(doesleftexist=0 && doesbottomexist=0): #we are at bottom left
sumation=matrix[rows-2][0]+matrix[rows-2][1]+matrix[rows-1][1]
... acordingly with different corners,
each different case is else if
if(doesbottomexist=0&&(doesleftexist==1 && doesrightexist==1)) #we are at bottom "not corner"
sumation=matrix[i][j-1]+matrix[i-1][j-1]+matrix[i-1][j]+matrix[i-1][j+1]+matrix[i][j+1]
... acordingly with different edges
each different case is else if
else:
sumation = [8 elements around the matrix[i][j]]
I didn't apply the list sumation, but it's easy just adding the incrementation of some dummy variable, knowing that you will go in each row by column.
It's kinda long and for sure not optimal solution to the problem (17 cases in total), but for sure it will give a solution for all matrixes, which are atleast 3x3.