蛇形方阵

蛇形填数
题目描述
在n×n方阵里填入1,2,…,n×n,要求填成蛇形。例如,n=4时方阵为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
上面的方阵中,多余的空格只是为了便于观察规律,不必严格输出。n≤8。
样例输入
4
样例输出
4
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
题意给定一个数,从右上角开始,按照下,左,右,上的顺序依次填入数字,行列的数字长度不能超过给定的值。
思路如果n=4,我们可以从1开始写,笔的坐标为(x,y)则x代表行,y代表列,1是第一行,第四(n)列,然后向下移,直到边界为止,然后向左移,接着向上移,向右,依次移动。
代码

#include <stdio.h>
#include<string.h>
int main()
{
    int n,x,y,t,a[20][20],tot;
    scanf("%d",&n);
    memset(a,0,sizeof(a));//全部初始化为0
    tot=a[x=1][y=n]=1;//下标,初始值赋为1
     while(tot<n*n)
        {
            while(x<n && a[x+1][y]==0) //下(不能出界且下一个格子的值是0)
                a[++x][y] = ++tot;
            while(y>1 && a[x][y-1]==0)//左
                a[x][--y] = ++tot;
            while(x>1 && a[x-1][y]==0) //上
                a[--x][y] = ++tot;
            while(y<n && a[x][y+1]==0) //右,
                a[x][++y] = ++tot;//(对于最后一个数来说tot的值赋给a[][]之后再加一 跳出循环)
        }
       /* 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(x=1;x<=n;x++)
        {
            for(y=1;y<=n;y++)
            printf("%3d",a[x][y]);
            printf("\n");
        }
    
    
    return 0;
    }

运行结果
在这里插入图片描述
总结

猜你喜欢

转载自blog.csdn.net/qq_43730272/article/details/89715712