公式

B - Magic Square 解説 by en_translator


Use loops and conditional branches to carefully implement what is described in the problem statement. Be cautious in creating two-dimensional arrays, and avoiding out-of-bounds array reference.

For more details, refer to the following sample code (C++ and Python).

Sample code (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' : ' ');
        }
    }
}

Sample code (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]))

投稿日時:
最終更新: