What's the most efficient way of traversing through all the adjacent cells of a particular cell in a 2D array?

Viewed 54

I am trying to find out the adjacent cells of a cell (i,j); which will be (i,j+1), (i,j-1), (i-1,j) and (i+1,j) in a 2D array.

My code to implement this:

for i in range(len(array)):

    for j in range(len(array)):

        if i==0:
            adjacent_row=[i,i+1]
        elif i==len(array)-1:
            adjacent_row=[i,i-1]
        else:
            adjacent_row=[i-1,i,i+1]

        if j==0:
            adjacent_column=[j]
        elif j==len(array)-1:                  # The column part is actually wrong, I don't know how to fix it
            adjacent_column=[j-1,j]
        else:
            adjacent_column=[j-1,j+1]

        for k in adjacent_row:

            for l in adjacent_column:

                #traverse through those cells

This was the idea that I had in my mind, but it's flawed.

1 Answers

For example you can do something like this

dx = [1,1,1,0,-1,-1,-1,0]
dy = [-1,0,1,1,1,0,-1,-1]
i = 2; j = 5 #The cell you want to have the neighbors
N = 10; M = 10 # Size of your array
neighbors = [] #Neighbors list
for x in dx:
    for y in dy:
        if i+x > 0 and i+x<N and j+y > 0 and j+y<M:
            neighbors.append(array[i+x,j+y])

Here I consider my array to be a numpy array but it don't change a lot of things

Related