zoukankan      html  css  js  c++  java
  • 蛇形填数字 (附书上例题答案)

    题目来自刘汝佳编著的《算法竞赛入门经典(第二版)》

    题目描述:

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

    10  11  12  1

     9   16  13  2

     8   15  14  3

     7     6    5  4

    我的代码(C++):

    #include<iostream>
    using namespace std;
    int main(){
        int n, i, j, m, time, t;
        int a[20][20];
        cin >> n;
        m = 1;
        i = 0;
        j = n-1;
        time = n*n;
        t = n;
        while (m <= time)
        {
            while (i <= n - 1) {
                a[i][j] = m; 
                m++; 
                i++;
            }
        
            i--;
            j--;
            while (j >= t-n) {
                a[i][j] = m; 
                m++;  
                j--;
            }
        
            j++;
            i--;
            while (i >= t-n) {
                a[i][j] = m; 
                m++; 
                i--;
            }
            
            i++;
            n--;
            j++;
            while (j <= n - 1) {
                a[i][j] = m; 
                m++; 
                j++;
            }
            
            j--;
            i++;
        }
        for (i = 0; i < t; i++)
        {
            for (j = 0; j < t; j++)
            {
                cout << a[i][j] << "     ";
                if (j == t - 1) cout << endl;
            }
        }
        return 0;
    }

    答案的代码(C):

    #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;
    }

    如果哪位大神有更加厉害的算法,请不要吝啬哦~o(* ̄▽ ̄*)ブ

  • 相关阅读:
    git配置config记住密码
    C#调用c++类的导出函数
    经典算法之直接插入排序
    经典算法之冒泡排序
    经典算法之二分查找
    shell实战之Linux主机系统监控
    shell高级特性-4
    shell实战之tomcat看门狗
    shell函数-3
    shell运算符与流程控制-2
  • 原文地址:https://www.cnblogs.com/Breathmint/p/7214153.html
Copyright © 2011-2022 走看看