所谓螺旋方阵,就是从外往里绕,如下图↓(4*4的螺旋方阵)
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
# include <iostream>
# include <cstring>
using namespace std;
int main(){
int a, z = 1, h = 0, l = 0;
cin >> a;
int sz1[a][a], x = a - 1;
memset(sz1, 0, sizeof(sz1));
while (true){
for (int n = 0; n < x; n++){
sz1[h][l] = z;
l++;
z++;
}
for (int j = 0; j < x; j++){
sz1[h][l] = z;
h++;
z++;
}
for (int i = 0; i < x; i++){
sz1[h][l] = z;
l--;
z++;
}
for (int c = 0; c < x; c++){
sz1[h][l] = z;
h--;
z++;
}
h++;
l++;
x -= 2;
if (z >= a * a){
if (a % 2 == 1){
sz1[int(a / 2)][int(a / 2)] = a * a;
}
break;
}
}
for (int y = 0; y < a; y++){
for (int u = 0; u < a; u++){
printf("%-5d", sz1[y][u]);
}
cout << "\n";
}
}