之字形打印一个矩阵 c++

之字形打印一个矩阵
1 2 3
4 5 6
7 8 9
打印结果是 1 2 4 7 5 3 6 8 9。要求额外空间复杂度是O(1)


#include <iostream>
#include <vector>
using namespace std;

void printMatrixZigZag (vector<vector<int> >matrix);
void printLevel(vector<vector<int> >matrix, int aRow, int aCol, int bRow, int bCol, bool upDown);
void print2DVector(vector<vector<int> >matrix);
vector<vector<int> > generateStandard2Dvector(int setRows, int setCols);

void printMatrixZigZag (vector<vector<int> >matrix){
    int aRow = 0;
    int aCol = 0;
    int bRow = 0;
    int bCol = 0;
    int endR = matrix.size() - 1;
    int endC = matrix[0].size() - 1;
    bool upDown = false;

    while (aRow <= endR ){
        printLevel (matrix, aRow, aCol, bRow, bCol, upDown);
        aRow = aCol == endC ? aRow + 1 : aRow;
        aCol = aCol == endC ? aCol : aCol + 1;
        bCol = bRow == endR ? bCol + 1: bCol;
        bRow = bRow == endR ? bRow : bRow + 1;
        upDown = !upDown;
    }
    cout <<  endl;
}

void printLevel(vector<vector<int> >matrix, int aRow, int aCol, int bRow, int bCol, bool f){
    if (f){
        while (aRow <= bRow ){
            cout << matrix[aRow++][aCol --] << " " ;
        }
    }
    else{
        while (aRow <= bRow ){
            cout << matrix[bRow--][bCol ++] << " " ;
        }
    }
}

void print2DVector(vector<vector<int> >matrix){
    int rows = matrix.size();
    int cols = matrix[0].size();
    for (int i = 0; i < rows; i++){
        for (int j = 0; j < cols; j++){
            cout << matrix[i][j];
            if (matrix[i][j] < 10)  cout << "  ";
            else cout<< " ";
        }
        cout << endl;
    }
}

vector<vector<int> > generateStandard2Dvector(int setRows, int setCols){
    int setNum = 0;
    vector<vector<int> >result;
    vector<int > tmp;

    if (setRows == 0 || setCols == 0){
        return result;
    }
    for (int row = 0; row < setRows; row++){
        tmp.clear();
        for (int col = 0; col < setCols; col ++){
            setNum ++;
            tmp.push_back(setNum);
        }
        result.push_back(tmp);
    }
    return result;
}

int main(){
    vector<vector<int> >matrix = generateStandard2Dvector(5,3);
    print2DVector(matrix);
    cout << endl;
    printMatrixZigZag(matrix);
    return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值