题目大意:输入n, 打印出n*n的数组,从周围一直向中心环绕递增, 如:
代码实现很简单:
#include <iostream>
#include <cstring>
#include <cstdio>
#define MAXN 100
using namespace std;
int a[MAXN][MAXN];
int main()
{
int n;
while(cin>>n)
{
memset(a,0,sizeof(a));
int tot,x,y;
tot = a[x=0][y=n-1] = 1;
while(tot<n*n)
{
while(x+1<n && !a[x+1][y]) a[++x][y] = ++tot;
while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++tot;
while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++tot;
while(y+1<n && !a[x][y+1]) a[x][++y] = ++tot;
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
printf("%3d",a[i][j]);
}
cout<<endl;
}
}
return 0;
}