已回答[标题][重复]

问题描述 投票:0回答:1

如何重新排列 4x4 网格中的数字,使总和为 0

问题解决了

stack-overflow
1个回答
1
投票

暴力破解版(没有任何优化):

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
© www.soinside.com 2019 - 2024. All rights reserved.