[算法竞赛入门]蛇形填数

蛇形填数。在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。

【解析】这道题的解题思路主要还是在于如何模拟蛇形填数的过程。

我们给出两个概念的定义:

(1)方向:该题中的方向顺序为“下-左-上-右”

(2)墙:填数过程中若遇到墙,则应改变方向。

【一种实现思路】注:这里我将n*n矩阵广义为n*m矩阵,令m=n.

#include <iostream>

#define MAX_LEN 100

using namespace std;

int a[MAX_LEN][MAX_LEN];

int main(){
    int n, m, x, y, c;

    while(cin >> n){
        c = 1;
        m = n;

        x = n - 1;
        y = 0;

        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = 0;
            }
        }
        a[y][x] = c++;
        while(c <= n * m){
            while(y + 1 < n && a[y + 1][x] == 0){//向下
                a[++y][x] = c++;
            }
            while(x - 1 >= 0 && a[y][x - 1] == 0){//向左
                a[y][--x] = c++;
            }
            while(y - 1 >= 0 && a[y - 1][x] == 0){//向上
                a[--y][x] = c++;
            }

            while(x + 1 < n && a[y][x + 1] == 0){//向右
                a[y][++x] = c++;
            }
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m - 1; j++){
                cout << a[i][j] << " ";
            }
            cout << a[i][m - 1] << endl;
        }
    }
    return 0;
}

 【测试数据】

 注:原创博客,转载请注明。

原文地址:https://www.cnblogs.com/Vivianwang/p/6432705.html