蛇形填数
描述在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
3 样例输出
7 8 1 6 9 2 5 4 3
#include<iostream>
#include<cstdio>
#include<cstring> //memset(a,0,size(a));
#include <iomanip>
using namespace std;
int main()
{
int a[100][100];
int n;
int x,y;
int count;
int i,j;
scanf("%d",&n);
// cin>>n;
memset(a,0,sizeof(a));
count=a[x=0][y=n-1]=1;
while(count<n*n)
{
//注意轮询的起始和条件
while(x+1<n &&a[x+1][y]==0) a[++x][y]=++count; //从一开始 右下依次增大
while(y-1>=0&&a[x][y-1]==0) a[x][--y]=++count; //往左依次增大
while(x-1>=0&&a[x-1][y]==0) a[--x][y]=++count; //左上依次增大
while(y+1<n &&a[x][y+1]==0) a[x][++y]=++count; // 往右依次增大
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);
if(j==n-1)
printf("\n");
}
/* for(x=0;x<n;x++){ //输出
for(y=0;y<n;y++){
cout<<setw(5)<<a[x][y];
}
cout<<endl;
}*/
return 0;
}