輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下4 X 4矩陣: 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:
// 首先判斷打印順時針圈的終止條件 :
// 當前行號 columns > startX * 2 rows > startY * 2
// 打印圈的四個步驟:
// 打印行從左到右 : end_columns > startX
// 打印列從上到下 : end_rows > startY
// 打印行從右到左 : end_columns > startX & end_rows > startY
// 打印列從下到上 : end_columns > startX & end_rows > startY + 1,最少有三行兩列
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> result;
if(matrix.empty()) return result;
int rows = matrix.size();
int cols = matrix[0].size();
int start = 0;
int index = 0;
while((rows > start * 2) && (cols > start * 2)){
int endY = rows - start - 1;
int endX = cols - start - 1;
//打印第一步
for(int i =start; i<= endX; i++) {
result.push_back(matrix[start][i]);
}
//打印第二步
if(start < endY)
for(int i =start+1; i<= endY; i++) {
result.push_back( matrix[i][endX]);
}
//打印第三步
if(start<endX && start <endY)
for(int i =endX-1; i >= start; i--) {
result.push_back(matrix[endY][i]);
}
//打印第四步
if(start<endX && start <endY -1)
for(int i =endY-1; i >= start +1; i--) {
result.push_back(matrix[i][start]);
}
start++;
}
return result;
}
};