蛇形填数 算法竞赛入门经典

#include <stdio.h>
#include "stdafx.h"
#include <iostream>
#include<time.h>
#include<iomanip>
#include<string.h>
#define maxn 20
using std::cin;
using std::cout;
int a[maxn][maxn];
int main() {
    int n, x, y, tot = 0;//tot可以看成一个标记,这个标记即是所跟随的坐标的数值
    cout << "请输入方块规模:" << std::endl;
    cin >> n;
    memset(a, 0, sizeof(a));
    tot = a[x = 0][y = n-1] = 1;
    if (n <= 8) {//四个while循环决定四个方向的坐标值变化,&&符号的后一个条件决定了在填数的过程中不会填过界
        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++) {
                cout << a[x][y]<<"    ";
            }
            cout << std::endl;
        }
    }
    else
        cout << "Wrong Size!!!" << std::endl;
}

猜你喜欢

转载自www.cnblogs.com/NK-007/p/9172795.html