码迷,mamicode.com
首页 > 其他好文 > 详细

NYOJ33 蛇形填数

时间:2014-07-16 15:34:54      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   for   io   

一、原题

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


三、解题思路

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

2.是否越界“预判”。

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

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

5.用for循环输出。

四、心得体会

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

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

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

NYOJ33 蛇形填数,布布扣,bubuko.com

NYOJ33 蛇形填数

标签:style   blog   color   使用   for   io   

原文地址:http://www.cnblogs.com/fightfor/p/3848155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!