题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
//if(matrix.empty())
vector<int> output;
int row = matrix.size();
int col = matrix[0].size();
int start = 0;
while(row > start * 2 && col > start * 2){
PrintMatixCircle(matrix, row, col, start, output);
start ++;
}
return output;
}
void PrintMatixCircle(vector<vector<int>> matrix, int row, int col, int start,vector<int>& output){
int endY = col - 1 - start;
int endX = row -1 - start;
//从左到右打印
for(int i = start; i <= endY; i ++){
output.push_back(matrix[start][i]);
}
//从上到下
if(start < endX){
for(int i = start +1; i <= endX; i ++){
output.push_back(matrix[i][endY]);
}
}
//从右向左打印
if(start < endX && start < endY){
for(int i = endY -1; i >= start; i --){
output.push_back(matrix[endX][i]);
}
}
//从下到上
if(start < endY && start < endX -1){
for(int i = endX -1; i >= start +1; -- i){
output.push_back(matrix[i][start]);
}
}
}
};