蛇形填数

在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 <iostream>
#include <cstdio>
#include <string.h>
#define max 20
using namespace std;
int a[max][max];
int main()
{
    int n;
    while(scanf("%d",&n) != EOF)
    {
        memset(a,0,sizeof(a));
        int x,y,num;
        x = 0;
        y = n-1;
        num = a[x][y] = 1;
        while(num < n*n)//如果去等,则意味着num = n*n时还要进入循环,事实上num = n*n时,结果已经做完了
        {
            while(x+1<n && !a[x+1][y]) a[++x][y] = ++num;//从上往下。这一题难的是条件的判断,while里应该为x+1<n,因为这个时候判断的是下个要填入的位置是否满足条件,以下同理
            while(y-1>=0 && !a[x][y-1]) a[x][--y] = ++num;//从右往左
            while(x-1>=0 && !a[x-1][y]) a[--x][y] = ++num;//从下往上
            while(y+1<n && !a[x][y+1]) a[x][++y] = ++num;//从左往右
        }
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
                printf("%3d ",a[i][j]);//为了数字对称,所以让每个输出占三个空格
            printf("\n");
        }
    }
    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值