結果

問題 No.217 魔方陣を作ろう
ユーザー kimiyukikimiyuki
提出日時 2016-12-06 18:52:51
言語 Python3
(3.11.6 + numpy 1.26.0 + scipy 1.11.3)
結果
AC  
実行時間 15 ms / 5,000 ms
コード長 1,794 bytes
コンパイル時間 811 ms
コンパイル使用メモリ 10,848 KB
実行使用メモリ 8,216 KB
最終ジャッジ日時 2023-08-18 19:36:07
合計ジャッジ時間 1,687 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 14 ms
8,216 KB
testcase_01 AC 13 ms
8,016 KB
testcase_02 AC 14 ms
8,112 KB
testcase_03 AC 14 ms
8,000 KB
testcase_04 AC 15 ms
8,032 KB
testcase_05 AC 15 ms
8,028 KB
testcase_06 AC 14 ms
8,144 KB
testcase_07 AC 13 ms
8,064 KB
testcase_08 AC 14 ms
8,068 KB
testcase_09 AC 13 ms
8,112 KB
testcase_10 AC 14 ms
8,192 KB
testcase_11 AC 14 ms
8,016 KB
testcase_12 AC 15 ms
8,060 KB
testcase_13 AC 14 ms
7,984 KB
testcase_14 AC 14 ms
8,148 KB
testcase_15 AC 14 ms
8,028 KB
testcase_16 AC 14 ms
8,012 KB
testcase_17 AC 15 ms
8,136 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#!/usr/bin/env python3
def magic_square(n):
    assert n >= 3
    f = [ [ None for _ in range(n) ] for _ in range(n) ]
    if n % 2 == 1: # http://d.hatena.ne.jp/ziom/20090619/p1
        y, x = 0, n//2
        for i in range(n**2):
            f[y%n][x%n] = i+1
            if f[(y-1)%n][(x+1)%n] is None:
                y, x = y-1, x+1
            else:
                y, x = y+1, x
    elif n % 4 == 0: # http://d.hatena.ne.jp/ziom/20090620/p1
        for y in range(n):
            for x in range(n):
                i = y*n+x+1
                if (y+1)&2 == (x+1)&2:
                    y = n-y-1
                    x = n-x-1
                f[y][x] = i
    else: # http://d.hatena.ne.jp/ziom/20090621/p1
        # [1,2n-2]
        f[  0][  0] = 1
        f[  0][n-1] = 2
        f[n-1][  1] = 3
        for i in range(4,2*n-1):
            if i <= n:
                x = i-2
                y = [n-1, 0][bool(i&2)]
                f[y][x] = i
                if i == n:
                    f[y][x] += 3
            else:
                y = i-n
                x = [n-1, 0][bool(i&2)]
                f[y][x] = i
                if i < n+4:
                    f[y][x] -= 1
        # [n^2-n+1,n^2]
        for i in range(1,n-1):
            for j in [ 0, n-1 ]:
                if f[  j][  i] is not None:
                    f[n-j-1][i] = n**2 - f[  j][  i] + 1
                if f[  i][  j] is not None:
                    f[i][n-j-1] = n**2 - f[  i][  j] + 1
        f[n-1][n-1] = n**2 - f[  0][  0] + 1
        f[n-1][  0] = n**2 - f[  0][n-1] + 1
        # recursion
        g = magic_square(n-2)
        for y in range(n-2):
            for x in range(n-2):
                f[y+1][x+1] = g[y][x] + 2*n-2
    return f
n = int(input())
for row in magic_square(n):
    print(*row)
0