之字形打印一个矩阵
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;
}