代码改变世界

蛇形填数

2014-12-15 22:19  星星之火✨🔥  阅读(537)  评论(0)    收藏  举报

题目取自:《算法竞赛入门经典》——刘汝佳

在 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。

我的程序:

#include<stdio.h>
#include<string.h>
#define MAXN 10
int a[MAXN][MAXN];
int main(void)
{
    int n, i, j;
    int value = 0;
    memset(a, 0, sizeof(a));
    scanf("%d", &n);
    for(i = 0; i <= n/2; i++) // 需要循环(n+1)/2次,因为共有n行,每次循环消除两行。
    {
        for(j = 0; j < n; j++)
            if(a[j][n-i-1] == 0) a[j][n-i-1] = ++value;
        for(j = n-1; j >= 0; j--)
            if(a[n-i-1][j] == 0) a[n-i-1][j] = ++value;
        for(j = n-1; j >= 0; j--)
            if(a[j][i] == 0) a[j][i] = ++value;
        for(j = 0; j < n; j++)
            if(a[i][j] == 0) a[i][j] = ++value;
    }

    for(i = 0; i < n; i++)
    {
        for(j = 0; j < n; j++)
            printf("%3d", a[i][j]);
        
        printf("\n");
    }    
    
    return 0;
}

/*
输入8时,
输出如下:
 22 23 24 25 26 27 28  1
 21 44 45 46 47 48 29  2
 20 43 58 59 60 49 30  3
 19 42 57 64 61 50 31  4
 18 41 56 63 62 51 32  5
 17 40 55 54 53 52 33  6
 16 39 38 37 36 35 34  7
 15 14 13 12 11 10  9  8
*/

作者程序:

分析:类比数学中的矩阵,我们可以用一个所谓的二维数组来储存题目中的方阵。只需声明一个int a[MAXN][MAXN],就可以获得一个大小为MAXN × MAXN 的方阵。在声明时,两维的大小不必相同,因此也可以声明int a[30][50]这样的数组,第一维下标范围是0,1,2,···,29,第二维下标范围是0,1,2,···,49。

我们从1开始依次填写。设"笔"的坐标为(x,y),则一开始x = 0,y= n-1,即第0行,第 n-1 列。"笔"的移动顺序是:先下,到了不能填为止,然后左、上、右。不能填是指再走就出界,或者再走就要走到以前填过的格子。如果把所有格子初始化为0,就能很方便地加以判断。

#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("\n");
    }
    
    return 0;
}