二维数组的螺旋方阵我认为还是比较难的,这个是填充螺旋方阵的代码
#include<bits/stdc++.h>
using namespace std;
int a[500][500], ans, n, m;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
//输入
cin >> n >> m;
//螺旋填充
ans = 1;
for (int i = 0; i < (min(n, m) + 1) / 2; i++) {
for (int j = i; j <= m - 1 - i; j++) {
a[i][j] = ans;
ans++;
}
for (int j = i + 1; j <= n - 1 - i; j++) {
a[j][m - 1 - i] = ans;
ans++;
}
if (i != n - 1 - i) {
for (int j = m - 2 - i; j >= i; j--) {
a[n - 1 - i][j] = ans;
ans++;
}
}
if (i != m - 1 - i) {
for (int j = n - 2 - i; j >= i + 1; j--) {
a[j][i] = ans;
ans++;
}
}
}
//输出
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (j < m - 1) cout << a[i][j] << " ";
else cout << a[i][j];
}
if (i < n - 1)cout << "\n";
}
return 0;
}