Last active
November 4, 2024 06:39
-
-
Save 003random/3e97ddc449aa394ebf25edb25c8c6110 to your computer and use it in GitHub Desktop.
get neighbors from a 2 dimensional array index in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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