公式

B - Magic Square 解説 by yuto1115

解説

繰り返しおよび条件分岐を用いて、問題文に書かれていることをそのまま丁寧に実装すればよいです。二次元配列の作り方、配列外参照などに注意してください。

詳細は下記の実装例 (C++, Python) を参考にしてください。

実装例 (C++) :

#include <bits/stdc++.h>

using namespace std;

int main() {
    int n;
    cin >> n;
    vector a(n, vector<int>(n));
    int r = 0, c = n / 2, x = 1;
    a[r][c] = x;
    while (x < n * n) {
        int nr = (r - 1 + n) % n, nc = (c + 1) % n;
        if (a[nr][nc] != 0) {
            nr = (r + 1) % n;
            nc = c;
        }
        a[nr][nc] = ++x;
        r = nr, c = nc;
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout << a[i][j] << (j == n - 1 ? '\n' : ' ');
        }
    }
}

実装例 (Python) :

n = int(input())
a = [[0] * n for _ in range(n)]

r = 0
c = n // 2
x = 1

a[r][c] = x

while x < n * n:
    nr = (r - 1 + n) % n
    nc = (c + 1) % n

    if a[nr][nc] != 0:
        nr = (r + 1) % n
        nc = c
    
    x += 1
    a[nr][nc] = x
    
    r = nr
    c = nc

for i in range(n):
    print(" ".join(str(j) for j in a[i]))

投稿日時:
最終更新: