Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save 003random/3e97ddc449aa394ebf25edb25c8c6110 to your computer and use it in GitHub Desktop.
Save 003random/3e97ddc449aa394ebf25edb25c8c6110 to your computer and use it in GitHub Desktop.
get neighbors from a 2 dimensional array index in python
def neighbors(matrix, rowNumber, colNumber):
result = []
for rowAdd in range(-1, 2):
newRow = rowNumber + rowAdd
if newRow >= 0 and newRow <= len(matrix)-1:
for colAdd in range(-1, 2):
newCol = colNumber + colAdd
if newCol >= 0 and newCol <= len(matrix)-1:
if newCol == colNumber and newRow == rowNumber:
continue
result.append(matrix[newCol][newRow])
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment