题解:B3940 [GESP样题 四级] 填幻方

· · 题解

双倍经验:P2615 [NOIP2015 提高组] 神奇的幻方

这道题很简单,模拟即可。

设幻方为 a,c 表示要填的数,则:

重复以上步骤,幻方就可以填好,代码如下(增加了防抄袭字符!):

#include <iostream>
using namespace std;
int a[23][23];
int main() {
    int n;
    cin >> n;
    a[1][n / 2 + 1] = 1;
    int cnt = 1;
    int x = 1, y = n / 2 + 1;
    while (cnt < n * n) {
        int nx = x, ny = y;
        nx = ((nx == 1) ? n : nx - 1);
        ny = ((ny == n) ? 1 : ny + 1);
        if (a[nx][ny] == 0) {
            a[nx][ny] = ++cnt;
            x = nx, y = ny;
            continue;
        }
        nx = x, ny = y;
        nx = ((nx == n) ? 1 : nx + 1);
        a[nx][ny] = ++cnt;
        x = nx, y = ny;
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cout << a[i][j] << ' ';
        }
        cout << endl;
    }
}