顺时针打印矩阵
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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) { vector<int> res; if(matrix.size()==0) return res; int start = 0; int rows = matrix.size(); int columns = matrix[0].size(); while(columns > start*2 && rows > start *2){ printCircle(matrix,columns,rows,start,res); ++ start; } return res; } void printCircle(vector<vector<int>> &matrix,int columns,int rows,int start,vector<int> & res){ int endX = columns - 1 - start; int endY = rows - 1 - start; for(int i = start; i <= endX; ++i){ int number = matrix[start][i]; res.push_back(number); } if(start < endY){ for(int i = start+1;i<=endY;++i){ int number = matrix[i][endX]; res.push_back(number); } } if(start < endX && start < endY){ for(int i = endX-1;i >= start;--i){ int number = matrix[endY][i]; res.push_back(number); } } if(start < endX && start < endY-1){ for(int i = endY -1;i>= start +1;--i){ int number = matrix[i][start]; res.push_back(number); } } } };