Files
python/GESP/资料/dad.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

38 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 40;
int n; //一个n*n的幻方
int g[N][N]; //一个二维数组用来存储幻方
int x, y; //用来记录上一个位置
int main() {
cin >> n;
//1≤N≤39 且 N 为奇数。
//(1)首先,将1写在第一行的中间
g[1][n / 2 + 1] = 1; // n/2+1,是因为n是奇数噢,偶数不用+1
//记录上一个放置的位置【这个很重要,一定要记录上一次的位置!!!】
x = 1;
y = n / 2 + 1;
//尝试将2-n^2的数字放入 [核心思想:上一个位置]
for (int i = 2; i <= n * n; i++) {
if (x == 1 && y != n) g[n][y + 1] = i, x = n, y++;
else if (y == n && x != 1) g[x - 1][1] = i, x--, y = 1;
else if (x == 1 && y == n)g[2][n] = i, x = 2;
else if (x != 1 && y != n) {
if (g[x - 1][y + 1] == 0) g[x - 1][y + 1] = i, x--, y++;
else g[x + 1][y] = i, x++;
}
}
//输出
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++)
cout << g[i][j] << " ";
cout << endl;
}
return 0;
}