### 像数独一样，在9 * 9矩阵中检查3 * 3矩阵是否重复

252 观看

1回复

43 作者的声誉

``````import numpy as np
def validSolution(board):

b=np.array(board)
b=np.vsplit(b,3)
for n,ar in enumerate(b):
b[n]=np.hsplit(ar,3)

for ar in b:
for arr in ar:
print(len(set(arr.flat))==len(arr.flat))

validSolution([[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]])
``````

### 回应 (1)

3

171499 作者的声誉

• 解决这个问题的一种方法将被重塑`a``4D``a4D`形状的`(3,3,3,3)`，从而每个窗口将是沿着第二和第四轴线。

• 我们需要扩展`b`到，`3D`以便第一根轴与的第二根轴对齐，第二根轴`a4D`与的第四根轴对齐`a4D`

• 进行比较，这是有效的，由NumPy广播提供，这给了我们一个`4D`布尔数组。在这两个暗处查找所有匹配项，然后简单地获取匹配索引。

``````np.argwhere((a.reshape(3,3,3,3) == b[:,None]).all((1,3)))
``````

``````In [190]: a
Out[190]:
array([[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]])

In [196]: b = a[-3:,-6:-3] # (2,1) grid

In [197]: b
Out[197]:
array([[5, 3, 7],
[4, 1, 9],
[2, 8, 6]])

In [198]: np.argwhere((a.reshape(3,3,3,3) == b[:,None]).all((1,3)))
Out[198]: array([[2, 1]])

In [199]: b = a[:3:,:3] # (0,0) grid

In [200]: b
Out[200]:
array([[5, 3, 4],
[6, 7, 2],
[1, 9, 8]])

In [201]: np.argwhere((a.reshape(3,3,3,3) == b[:,None]).all((1,3)))
Out[201]: array([[0, 0]])
``````

``````In [206]: from skimage.util.shape import view_as_blocks

In [207]: np.argwhere((view_as_blocks(a, b.shape) == b).all((2,3)))
Out[207]: array([[0, 0]])
``````