zoukankan      html  css  js  c++  java
  • 蛇形填数

    蛇形填数。

    在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 20
    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;
    }
            

    这段程序充分利用了C语言简洁的优势。

    首先,赋值x=0和y=n-1后马上要把它们 作为数 组a的下标,因此可以合并完成;

    tot和a[0][n-1]都要赋值1,也可以合并完成。

    这样,就用一 条语句完成了多件事情,而且并没有牺牲程序的可读性——这段代码的含义显而易见。

  • 相关阅读:
    02.CentOS Linux 7.7 Nginx安装部署文档
    rpm操作
    mysql命令行备份方法
    nginx reload的原理
    Linux操作笔记
    mysql账户授权
    centos系统内核升级
    docker随笔
    linux系统查看当前正在运行的服务
    数据库锁表问题
  • 原文地址:https://www.cnblogs.com/LOW-ctfer/p/10329068.html
Copyright © 2011-2022 走看看