螺旋矩阵就是形如如下图的矩阵:
看到矩阵知道它由四条边组成,这样的话就有这样的n/2个环,但是如果是奇数矩阵的话在最中间需要特殊处理一下:
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<iomanip>
#include<queue>
#define pi acos(-1)
#define For(i, a, b) for(int (i) = (a); (i) <= (b); (i) ++)
#define Bor(i, a, b) for(int (i) = (b); (i) >= (a); (i) --)
using namespace std;
typedef long long ll;
const int maxn = 100 + 10;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-10;
const ll mod = 1e9 + 7;
inline int read(){
int ret=0,f=0;char ch=getchar();
while(ch>'9'||ch<'0') f^=ch=='-',ch=getchar();
while(ch<='9'&&ch>='0') ret=ret*10+ch-'0',ch=getchar();
return f?-ret:ret;
}
int n;
int a[maxn][maxn];
int main(){
ios::sync_with_stdio(false);
cin >> n;
int t = n/2;
int i = 0;
int j = 0;
int ans = n;
int st = 1;
for(int num =0;num < t; num++){
for(; j < ans - 1; j++)a[i][j] = st++;
for(; i < ans - 1; i++)a[i][j] = st++;
for(j = ans -1; j > num; j--)a[i][j] = st ++;
for(i = ans -1; i > num; i--)a[i][j] = st ++;
i++,ans--,st -= 1;
}
if(n%2!=0)a[i][j+1]=st+1;
for(i=0;i<n;i++){
for(j=0;j<n;j++)
cout<<setw(3)<<a[i][j];
cout<<endl;
}
return 0;
}