题目要求:打印螺旋矩阵
1 2 3 4 5 6 7
24 25 26 27 28 29 8
23 40 41 42 43 30 9
22 39 48 49 44 31 10
21 38 47 46 45 32 11
20 37 36 35 34 33 12
19 18 17 16 15 14 13
#include <bits/stdc++.h>
using namespace std;
const int maxn = 60;
int arr[maxn][maxn];
int n;
void spiralMatrix(int s, int len, int k){
if(len == 1){
arr[k][k] = s;
return ;
}else if(len == 2){
arr[k][k] = s++;
arr[k][k + 1] = s++;
arr[k + 1][k + 1] = s ++;
arr[k + 1][k] = s;
return ;
}
int col = len + 1 - k;
for(int j = k; j <= col; j++)
arr[k][j] = s++;
for(int i = k + 1; i <= col; i++)
arr[i][col] = s++;
for(int j = col -1; j >= k; j--)
arr[col][j] = s++;
for(int i = col -1; i >= k + 1; i--)
arr[i][k] = s++;
spiralMatrix(s,len - 2, k + 1);
}
void print_spiralMtrix(){
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= n;j++)
{
printf("%5d", arr[i][j]);
}
cout << endl;
}
}
int main(){
cin >> n;
spiralMatrix(1,n,1);
print_spiralMtrix();
return 0;
}