蛇形矩阵

  今天看到一个比较有趣的问题,输入一个整数n,输出一个n*n的矩阵,矩阵是逆时针方向增长的蛇形矩阵。这到底是个什么矩阵呢?举例来说:输入3,输出应该是

            1 2 3
            8 9 4
            7 6 5 

我的思路就是按照逆时针的方向来增大矩阵,num从1一直增大到n*n为止,增长方向由right,down,left,up4个bool值来控制,同时还设置了4个边界来控制i和j的终止范围,代码写得并不好,思路太过原始,变量也多,应该有一些简单的算法,不过暂时想把我这种思路记录下来吧,附代码:

#include
#include
using namespace std;

const int MAX = 10000;
int a[MAX][MAX];


//逆时针增加的蛇形矩阵 
void snake(int N){
    bool right = true, down = false, left = false, up = false;  //4个方向 
    int startOfI = 0, startOfJ = 0;
    //4个边界 
    int boundOfJRight = N, boundOfJLeft = 0;
    int boundOfIBottom = N, boundOfITop = 0;
    //i和j的起始位置
    int i = startOfI, j = startOfJ;
    int num = 0;
    while(num < N*N){
        //先向右增加 
        if(right){
            for(j = startOfJ; j < boundOfJRight; j++){
                num++;
                a[startOfI][j] = num;
                cout << "第" << startOfI << "行\t第" <"列" << num << endl; 

            }
            right = !right;
            down = !down;
            startOfJ = j-1;
            startOfI++;
            //向右增加完成后,顶层肯定会铺满一层,所以顶层边界要加1
            boundOfITop++;

        }
        //向下 
        if(down){
            for(i = startOfI; i < boundOfIBottom; i++){
                num++;
                a[i][startOfJ] = num;
                cout << "第" << i << "行\t第" << startOfJ << "列" << num << endl;

            }
            down = !down;
            left = !left;
            startOfI = i-1;
            startOfJ--;
            //同理,向下增加完成后,右边肯定会铺满一列,所以右边边界要减1
            boundOfJRight--;

        }
        //向左 
        if(left){
            for(j = startOfJ; j >= boundOfJLeft; j--){
                num++;
                a[startOfI][j] = num;
                cout << "第" << startOfI << "行\t第" <"列" << num << endl;

            }
            left = !left;
            up = !up;
            startOfJ = j+1;
            startOfI--;
            //向左增加完成后,底层肯定会铺满一层,所以底层边界要减1
            boundOfIBottom--;
        }
        //向上 
        if(up){
            for(i = startOfI; i >= boundOfITop; i--){
                num++;
                a[i][startOfJ] = num;
                cout << "第" << i << "行\t第" << startOfJ << "列" << num << endl;

            }
            up = !up;
            right = !right;
            startOfI = i+1;
            startOfJ++;
            //向上增加完成后,左边肯定会铺满一列,所以左边边界要加1
            boundOfJLeft++;
        }
    }

    //打印 
    for(int k = 0; k < N; k++){
        for(int p = 0; p < N; p++){
            cout <5) << a[k][p] ;
        }
        cout << endl;
    }
}


int main(){
    int n;
    cin >> n;
    snake(n);
}

运行结果示例:
蛇形矩阵_第1张图片
n = 6
蛇形矩阵_第2张图片

你可能感兴趣的:(C++,C++,算法)