Search code examples
pythonpython-3.xalgorithmnumpyimplementation

How to access the adjacent cells of each elements of matrix in python?


Here two cells are considered adjacent if they share a boundary. For example :

A = 5 6 4
    2 1 3
    7 9 8

Here adjacent elements to index 0,0 is at index [0,1] and [1,0] and for index 1,1 the adjacent elements are at index [0,1],[1,0],[2,1] and [1,2].


Solution

  • Supposed you have mxn matrix, and you want to find the adjacent indices of the cell (i, j):

    def get_adjacent_indices(i, j, m, n):
       adjacent_indices = []
        if i > 0:
            adjacent_indices.append((i-1,j))
        if i+1 < m:
            adjacent_indices.append((i+1,j))
        if j > 0:
            adjacent_indices.append((i,j-1))
        if j+1 < n:
            adjacent_indices.append((i,j+1))
        return adjacent_indices