蛇形填數

在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 <cstring>
using namespace std;
#define maxn 20
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("%5d", a[x][y]);
                cout << "\n";
        }
        return 0;
}

ps. 

x+1 < n,  y - 1 >= 0 的判斷,是爲了提前判斷,因爲循環體中會修改下一個變量。循環條件是爲了判斷下一個變量是否符合條件。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章