NYOJ33 蛇形填数

一、原题

在n*n方阵里填入1,2,...,n*n.要求填成蛇形.例如n=4时方阵为:

  10  11  12  1

    9  16  13  2

    8  15  14  3

    7    6    5  4

(题目来源:《算法竞赛入门经典》【刘汝佳】)

二、题目源代码

#include <stdio.h>
#include <string.h>
#define MAXN 10
int a[MAXN][MAXN];
int main()
{

    int n,x,y,tot=0;
    scanf("%d",&n);
    memset(a,0,sizeof(a));
    tot=a[x=0][y=n-1]=1;
    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=0;x<n;x++)
    {
        for(y=0;y<n;y++)  printf("%3d",a[x][y]);
        printf("
");
    }
    return 0;
}


三、解题思路

1.首先生成一个整型二维数组代表方阵。

2.是否越界“预判”。

3.下一个格子中是否已经装了东西“预判”。

4.用while判断后,实现数字递增

5.用for循环输出。

四、心得体会

1.对MAXN进行赋值之后再定义int a[MAXN][MAXN]。

2.a[x=0][y=n-1]的表示方法。

3.“=”与“==”使用时要注意,完全不同!