Finding neighbours in a two-dimensional array

后端 未结 20 1192
忘了有多久
忘了有多久 2020-11-30 02:02

Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding

20条回答
  •  旧巷少年郎
    2020-11-30 02:40

    This is an implementation of @Seb's answer in python3+ that is concise and uses generators for max performance:

    def neighbours(pos, matrix):
        rows = len(matrix)
        cols = len(matrix[0]) if rows else 0
        for i in range(max(0, pos[0] - 1), min(rows, pos[0] + 2)):
            for j in range(max(0, pos[1] - 1), min(cols, pos[1] + 2)):
                if (i, j) != pos:
                    yield matrix[i][j]
    

提交回复
热议问题