Skip to content

M07207: 神奇的幻方

implementation, matrices, http://cs101.openjudge.cn/practice/07207/

幻方是一个很神奇的N*N矩阵,它的每行、每列与对角线,加起来的数字和都是相同的。 我们可以通过以下方法构建一个幻方。(阶数为奇数) 1.第一个数字写在第一行的中间 2.下一个数字,都写在上一个数字的右上方: a.如果该数字在第一行,则下一个数字写在最后一行,列数为该数字的右一列 b.如果该数字在最后一列,则下一个数字写在第一列,行数为该数字的上一行 c.如果该数字在右上角,或者该数字的右上方已有数字,则下一个数字写在该数字的下方

输入

一个数字N(N<=20)

输出

按上方法构造的2N-1 * 2N-1的幻方

样例输入

3

样例输出

17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

思路:

  1. 创建 M×M 的矩阵,初始化为 0。
  2. 从位置 (0, M//2) 开始放置数字 1。
  3. 按规则依次放置 2 到 M² 的数字。
python
def construct_magic_square(N):
    M = 2 * N - 1
    # 创建 M x M 的矩阵,初始为0
    magic = [[0] * M for _ in range(M)]

    # 初始位置:第一行,中间列
    row, col = 0, M // 2
    magic[row][col] = 1

    # 填充 2 到 M*M
    for num in range(2, M * M + 1):
        # 计算下一个位置:上一行,右一列(边界循环)
        next_row = (row - 1) % M
        next_col = (col + 1) % M

        # 如果目标位置已经有数字,就放在正下方
        if magic[next_row][next_col] != 0:
            next_row = (row + 1) % M  # 正下方,注意也可能越界,用 % M
            next_col = col

        # 放置当前数字
        magic[next_row][next_col] = num
        # 更新当前位置
        row, col = next_row, next_col

    return magic


def print_magic_square(magic):
    M = len(magic)
    for i in range(M):
        # 将每行数字转为字符串,用空格连接
        print(" ".join(str(magic[i][j]) for j in range(M)))


# 主程序
if __name__ == "__main__":
    N = int(input().strip())
    square = construct_magic_square(N)
    print_magic_square(square)
python
# 23n2300011031
n=int(input())
t=n+n-1
l=[[0]*t for _ in range(t)]
i,j=0,n-1
for k in range(1,1+t**2):
    l[i][j]=k
    if (i==0 and j==t-1) or l[(i-1)%t][(j+1)%t]!=0:
        i,j=(i+1)%t,j
    else:
        i,j=(i-1)%t,(j+1)%t
for u in l:
    print(*u)
python
# 23n2300017735(夏天明BrightSummer)
N = int(input())
mat = [[0]*(2*N-1) for j in range(2*N-1)]
pos = [0, N-1]
val = 1
while val <= (2*N-1)**2:
    mat[pos[0]%(2*N-1)][pos[1]%(2*N-1)] = val
    val += 1
    pos[0] -= 1
    pos[1] += 1
    if mat[pos[0]%(2*N-1)][pos[1]%(2*N-1)] != 0:
        pos[0] += 2
        pos[1] -= 1
for row in mat:
    print(*row)