我那就是简单
2025-06-23 14:16:38
发布于:上海
0阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<vector<int>> a(n, vector<int>(n, 0));
int x = 0, y = n / 2;
a[x][y] = 1;
for (int k = 2; k <= n * n; ++k) {
int prev_x = x, prev_y = y;
// Case 1: previous is in first row but not last column
if (prev_x == 0 && prev_y != n - 1) {
x = n - 1;
y = prev_y + 1;
}
// Case 2: previous is in last column but not first row
else if (prev_y == n - 1 && prev_x != 0) {
x = prev_x - 1;
y = 0;
}
// Case 3: previous is in first row and last column
else if (prev_x == 0 && prev_y == n - 1) {
x = prev_x + 1;
y = prev_y;
}
// Case 4: general case
else {
if (a[prev_x - 1][prev_y + 1] == 0) {
x = prev_x - 1;
y = prev_y + 1;
} else {
x = prev_x + 1;
y = prev_y;
}
}
a[x][y] = k;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << a[i][j];
if (j != n - 1) cout << " ";
}
cout << endl;
}
return 0;
}
这里空空如也
有帮助,赞一个