暴力破解版(没有任何优化):
from itertools import permutations
import numpy as np
matrices = [
matrix1,
matrix2,
matrix3,
matrix4,
matrix5,
matrix6,
matrix7,
matrix8,
matrix9,
]
for c in permutations(matrices, 9):
r1 = np.r_[c[0], c[1], c[2]]
r2 = np.r_[c[3], c[4], c[5]]
r3 = np.r_[c[6], c[7], c[8]]
f = np.c_[r1, r2, r3]
row_sums = f.sum(axis=1)
if np.allclose(row_sums, [9, 4, 9, 5, 2, 5, 4, 3, 4]):
col_sums = f.sum(axis=0)
if np.allclose(col_sums, [5, 4, 5, 7, 4, 7, 5, 4, 4]):
if f.diagonal().sum() == 6 and np.fliplr(f).diagonal().sum() == 6:
print("Solution:")
print(f)
break
打印(在我的 AMD 5700x 上大约需要 13 秒):
Solution:
[[1 1 1 1 1 1 1 1 1]
[1 1 1 0 0 0 1 0 0]
[1 1 1 1 1 1 1 1 1]
[0 0 1 1 0 1 1 0 1]
[0 1 0 0 0 0 0 1 0]
[1 0 0 1 0 1 1 0 1]
[0 0 1 1 1 1 0 0 0]
[0 0 0 1 0 1 0 1 0]
[1 0 0 1 1 1 0 0 0]]
real 0m13,802s
user 0m0,008s
sys 0m0,008s