简体   繁体   English

获取NxN网格python的邻居

[英]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). 我正在尝试创建一种算法来创建矩阵P,对于NxN网格,所有矩阵都用值X注释(在矩阵P中)。

So for example I have a 3x3 grid: 例如,我有一个3x3的网格:

0   1   2
3   4   5
6   7   8

The neighbors of (0) are (1) and (3). (0)的邻居是(1)和(3)。 The neighbors of (7) are (4), (6) and 8 etc. Therefore matrix P should turn into: (7)的邻居是(4),(6)和8等。因此,矩阵P应该变成:

[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. 但是,我无能为力地将其转换为2D方式。 Does anyone know how to do this? 有谁知道如何做到这一点?

Each 'row' in P actually represents a 'row' and 'col' in the 3x3 grid. P中的每个“行”实际上代表3x3网格中的“行”和“ col”。 To convert from the row number in P to the grid coordinates takes two lines of code: 从P中的行号转换为网格坐标需要两行代码:

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 . 第二行使用模运算符,这是将i除以N时的余数。

Likewise, each 'col' in P is converted to other_row and other_col in the 3x3 grid. 同样,P中的每个“ col”在3x3网格中都转换为other_rowother_col

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM