题目:顺时针打印矩阵
要求:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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: vector<int> printMatrix(vector<vector<int> > matrix) { } };
解题代码:
1 class Solution { 2 public: 3 vector<int> printMatrix(vector<vector<int> > matrix) { 4 int rows = matrix.size(); 5 int cols = matrix[0].size(); 6 vector<int> res; 7 8 int start = 0; 9 while(cols > start * 2 && rows > start * 2){ 10 printMatrixInCircle(matrix, rows, cols, start, res); 11 start++; 12 } 13 return res; 14 } 15 16 private: 17 void printMatrixInCircle(vector<vector<int> > matrix, int rows, int cols, int start, vector<int> &res){ 18 int endX = cols - 1 - start; 19 int endY = rows - 1 - start; 20 21 // 从左到右 22 for(int i = start; i <= endX; i++) 23 res.push_back(matrix[start][i]); 24 25 // 从上到下 26 if(start < endY){ 27 for(int i = start + 1; i <= endY; i++) 28 res.push_back(matrix[i][endX]); 29 } 30 31 // 从右到左 32 if(start < endX && start < endY){ 33 for(int i = endX - 1; i >= start; i--) 34 res.push_back(matrix[endY][i]); 35 } 36 37 // 从下到上 38 if(start < endX && start < endY - 1){ 39 for(int i = endY - 1; i > start; i--) 40 res.push_back(matrix[i][start]); 41 } 42 } 43 };