蛇形填数


#include<stdio.h>
#include<string.h>
int main()
{
    int a[10][10], n,tot= 0, x, y;
     memset(a, 0, sizeof(a));//刚开始将数组元素全部清零
    tot = a[x=0][y=0] = 1;
    
    scanf("%d", &n);
    while(tot < n*n)//按蛇形右下左上 不能填已经走过的格子 和不能越界
    {
    while(y < n-1 && !a[x][y+1])
        a[x][++y] = ++tot;
    while(x < n-1 && !a[1+x][y])
        a[++x][y] = ++tot;
    while(x >= 1 && !a[x-1][y])
        a[--x][y] = ++tot;
    while(y >= 1 && !a[x][y-1])
        a[x][--y] = ++tot;
    }
    for(x = 0; x < n; x++)
    {
        for(y = 0; y < n; y++)
            printf("%3d",a[x][y]);
        printf("\n");
    }

}



posted @ 2016-04-16 14:08  云胡同学  阅读(128)  评论(0编辑  收藏  举报