我正在尝试创建一种算法来创建矩阵P,对于NxN网格,所有矩阵都用值X注释(在矩阵P中)。
例如,我有一个3x3的网格:
0 1 2
3 4 5
6 7 8
(0)的邻居是(1)和(3)。 (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],
我使它可以在一维中工作
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
但是,我无能为力地将其转换为2D方式。有谁知道该怎么做?
答案 0 :(得分:1)
P中的每个“行”实际上代表3x3网格中的“行”和“ col”。要从P中的行号转换为网格坐标,需要两行代码:
current_row = i // N
current_col = i % N
第一行正在进行整数除法,这意味着它会四舍五入为最接近的整数。第二行使用模运算符,这是将i
除以N
时的余数。
同样,P中的每个'col'在3x3网格中都转换为other_row
和other_col
。
一旦知道了行和列,其余的代码就非常简单了:
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