题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
题目分析:
1 2 3 4
5 6 7 8
10 11 12 13
14 15 16 17
每次的起点都是左上角(0,0) (1,1),终止条件为坐标的2倍分别小于行数列数。
分为4个方向走:
上:必然执行
右:行数要大于2
下:行数列数均大于2
左:行数大于3,列数大于2
从外圈走入最里圈结束。
class Solution {
public:
vector<int>res;
vector<int> printMatrix(vector<vector<int> > matrix) {
int rows = (int)matrix.size();
int columns = (int)matrix[0].size();
if(rows == 0||columns == 0)
return res;
int start = 0;
while(start*2<rows && start*2<columns){
printStart(matrix,start,rows,columns);
start++;
}
return res;
}
void printStart(vector<vector<int> > matrix,int start,int rows,int columns){
int endX = columns - start -1 ;
int endY = rows -start - 1;
//up
for (int i = start; i <= endX; ++i) {
res.push_back(matrix[start][i]);
}
//right
if(endY > start){
for (int i = start+1; i <= endY; ++i) {
res.push_back(matrix[i][endX]);
}
}
//down
if(endX>start&&endY>start){
for (int i = endX-1; i >=start ; i--) {
res.push_back(matrix[endY][i]);
}
}
//left
if(endY>start+1&&endX>start){
for (int i = endY-1; i >start ; i--) {
res.push_back(matrix[i][start]);
}
}
}
};