蛇形填数(模拟)

#include<cstdio>
#include<cstring>
using namespace std;
int a[10][10];
int main()
{
    int n,x,y,tot;
    scanf("%d",&n);
    memset(a,0,sizeof(a));
    a[x=1][y=n]=1;tot=1;
    while(tot<n*n)
    {
        while(x+1<=n&&a[x+1][y]==0) a[++x][y]=++tot;//一直往一个方向填,直到填不了 
        while(y-1>=1&&a[x][y-1]==0) a[x][--y]=++tot;//一直往一个方向填,直到填不了
        while(x-1>=1&&a[x-1][y]==0) a[--x][y]=++tot;//一直往一个方向填,直到填不了
        while(y+1<=n&&a[x][y+1]==0) a[x][++y]=++tot;//一直往一个方向填,直到填不了
    }//&&为短路运算符,原理是若左边为假,则右边不会运行,所以不必考虑越界 
    for(int i=1;i<=n;++i)
    {
      for(int j=1;j<=n;++j)
    printf("%3d",a[i][j]);
       printf("\n");
    }
}

猜你喜欢

转载自www.cnblogs.com/czy0130/p/9497142.html