vector<int> printMatrix(vector<vector<int> > matrix) {
if(matrix.empty())
cerr<<"wrong input" ;
int raw_end=matrix.size()-1;
int col_end=matrix[0].size()-1;
int raw_start=0;
int col_start=0;
vector<int> result;
while(raw_start<=raw_end&&col_start<=col_end){
FindMatrix(matrix,raw_start,raw_end,col_start,col_end,result);
raw_start=raw_start+1;
raw_end=raw_end-1;
col_start=col_start+1;
col_end=col_end-1;
}
return result;
}
vector<int> FindMatrix(const vector<vector<int> >& matrix,int raw_start,int raw_end,int col_start,int col_end,vector<int>& result){
for(int j=col_start;j<=col_end;j++)
result.push_back(matrix[raw_start][j]);
if(raw_end>raw_start){//从上到下打印一列->至少要两行
for(int i=raw_start+1;i<=raw_end;i++)
result.push_back(matrix[i][col_end]);
}
if(raw_end>raw_start&&col_end>col_start){//从右向左打印一行->至少要两行两列
for(int j=col_end-1;j>=col_start;j--)
result.push_back(matrix[raw_end][j]);
}
if(raw_end>raw_start+1&&col_end>col_start){//从下到上打印一列->至少要三行两列
for(int i=raw_end-1;i>=raw_start+1;i--)
result.push_back(matrix[i][col_start]);
}
return result;
}
面试题29:顺时针打印矩阵
最新推荐文章于 2020-12-21 07:33:17 发布