View Code
#include"iostream"
using namespace std;
int main()
{
int n,i,j;
int b[720][720];
while(cin>>n)
{
memset(b,0,sizeof(b));
if(n==1) cout<<n<<endl;
else
{
i=1,j=1;
int k=1;
for(int t=1; t<n ; t++)
{
while(j<=n-i+1&&j>=i) //横行->rigth
{
b[i][j]=k++;
if(k==n*n) break;
j++;
}
if(k-1==n*n) break;
j--;
while(i<j&&i>=n-j+1) //竖行down
{
i++;
b[i][j]=k++;
if(k-1==n*n) break;
}
if(k-1==n*n) break;
while(j>n-i+1) //横行lift
{
j--;
b[i][j]=k++;
if(k-1==n*n) break;
}
i--;
if(k-1==n*n) break;
while(i>j&&i<n-j+1) //竖行up
{
b[i][j]=k++;
if(k-1==n*n) break;
i--;
}
if(k-1==n*n) break;
i++;j++;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d",b[i][j]);
if(j<=n) cout<<" ";
}
cout<<endl;
}
}
}
return 0;
}