You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求简化3×3幻方生成的技术实现方案

简化3×3幻方生成与最小转换代价计算

3×3的幻方其实只有1种基础结构,通过旋转(90°、180°、270°)和水平/垂直翻转,可以得到全部8种合法的3×3幻方。因此不需要复杂的动态生成逻辑,直接预定义所有可能的幻方是最简洁高效的方案。

以下是计算将给定方阵转换为幻方所需最小代价的Python实现:

def getCost(arr, magic):
    return sum(abs(arr[i][j] - magic[i][j]) for i in range(3) for j in range(3))

def formingMagicSquare(s):
    # 预定义所有8种合法的3×3幻方
    magic_squares = [
        [[8, 1, 6], [3, 5, 7], [4, 9, 2]],
        [[6, 7, 2], [1, 5, 9], [8, 3, 4]],
        [[2, 9, 4], [7, 5, 3], [6, 1, 8]],
        [[4, 3, 8], [9, 5, 1], [2, 7, 6]],
        [[6, 1, 8], [7, 5, 3], [2, 9, 4]],
        [[2, 7, 6], [9, 5, 1], [4, 3, 8]],
        [[4, 9, 2], [3, 5, 7], [8, 1, 6]],
        [[8, 3, 4], [1, 5, 9], [6, 7, 2]]
    ]

    minCost = float('inf')
    for square in magic_squares:
        cost = getCost(square, s)
        minCost = min(minCost, cost)
    return minCost

代码说明

  • getCost函数:计算两个3×3方阵之间的转换代价,即对应位置元素差值的绝对值之和。
  • formingMagicSquare函数:遍历预定义的所有幻方,计算每个幻方与输入方阵的转换代价,返回最小的代价。

内容的提问来源于stack exchange,提问作者Ignis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:55:04