A clockwise print matrix
class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { vector<int> result; int m = matrix.size(); if (m==0) return result; int n = matrix[0].size(); if (n==0) return result; int start=0; while(start < m/2.0Start && <n-/ 2.0 ) { printCircle (Matrix, Start, m, n-, Result); Start ++ ; } return Result; } // first judgment, split into Circle Print, // determine the change in the start and end ( See coordinates, coordinates of the start and end of the addition and the same) // four sequentially except the first one, the rest are conditional, and to perform a post must meet all the conditions previously. Private : void printCircle (Vector <Vector < int >> Matrix, int Start, int m, int n-, Vector < int > & Result) { int end_x = n-- . 1 - Start; int end_y = m - 1 - start; // 从左到右 for (int i = start; i <= end_x; i++) result.push_back(matrix[start][i]); // 从上到下 if (end_y > start) { for (int i = start+1; i <= end_y; i++) result.push_back(matrix[i][end_x]); } // 从右到左 if (end_x - 1 >= start && end_y > start) { for (int i= end_x-1; i>=start; i--) result.push_back(matrix[end_y][i]); } // 从下到上 if (end_y - 1 > start && end_x -1 >= start) { for (int i= end_y - 1; i>= start+1; i--) result.push_back(matrix[i][start]); } } };
Reproduced in: https: //www.cnblogs.com/cookcoder-mr/p/11123310.html