Steven
Steven

Reputation: 1173

Get neighbors of NxN grid python

I'm trying to make an algorithm to create a matrix P in such a way that for a NxN grid all the have are annotated with value X (in matrix P).

So for example I have a 3x3 grid:

0   1   2
3   4   5
6   7   8

The neighbors of (0) are (1) and (3). The neighbors of (7) are (4), (6) and 8 etc. Therefore matrix P should turn into:

[1, X, 0, 0, 0, 0, 0, 0, 0],
[X, 1, X, 0, X, 0, 0, 0, 0],
[0, X, 1, 0, 0, X, 0, 0, 0],
[X, 0, 0, 1, X, 0, X, 0, 0],
[0, X, 0, X, 1, X, 0, X, 0],
[0, 0, X, 0, X, 1, 0, 0, X],
[0, 0, 0, X, 0, 0, 1, X, 0],
[0, 0, 0, 0, X, 0, X, 1, X],
[0, 0, 0, 0, 0, X, 0, X, 1],

I got it working in 1D:

for i in range(N):
    for j in range(N):
        if i == j:
            p[i][j] = 1
        else:
            if j + 1 == i:
                p[i][j] = X
            elif j - 1 == i:
                p[i][j] = X

However, I'm clueless trying to turn this into the 2D way. Does anyone know how to do this?

Upvotes: 0

Views: 517

Answers (1)

user3386109
user3386109

Reputation: 34829

Each 'row' in P actually represents a 'row' and 'col' in the 3x3 grid. To convert from the row number in P to the grid coordinates takes two lines of code:

current_row = i // N
current_col = i % N

The first line is doing integer division, meaning that it rounds down to the nearest integer. The second line is using the modulo operator, which is the remainder when dividing i by N.

Likewise, each 'col' in P is converted to other_row and other_col in the 3x3 grid.

Once the rows and cols are known, the rest of the code is pretty straightforward:

N = 3
p = [['0' for col in range(N*N)] for row in range(N*N)]
for i in range(N*N):
   for j in range(N*N):
      current_row = i // N
      current_col = i % N
      other_row = j // N
      other_col = j % N
      if current_row == other_row and current_col == other_col:
         p[i][j] = '1'
      elif current_row == other_row and abs(current_col - other_col) == 1:
         p[i][j] = 'X'
      elif current_col == other_col and abs(current_row - other_row) == 1:
         p[i][j] = 'X'

for i in range(N*N):
   for j in range(N*N):
      print p[i][j],
   print

Upvotes: 1

Related Questions