首页 > 其他 > 详细

蛇形填数

时间:2019-03-16 16:38:40      阅读:144      评论:0      收藏:0      [点我收藏+]

   在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

解题思路:

我们可以了解到数字的大概规律就是先从上到下,到左,到上,到右这个顺序填写,我们只要注意临界点即可。

//
//  main.cpp
//  c++prime
//
//  Created by SJCHEN on 2019/1/19.
//  Copyright © 2019 SJCHEN. All rights reserved.
//

#include <iostream>
#include <cstdio>
using namespace std;
#define MAXN 10
int a[MAXN][MAXN];

int main()
{
    int n,x,y,tot = 0;
    cin >> 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]);
        cout << endl;
    }
    return 0;
}

 

蛇形填数

原文:https://www.cnblogs.com/SJCHEN/p/10542708.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!