一 顺时针打印矩阵
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.0 && start < n/2.0) { printCircle(matrix, start, m, n, result); start++; } return result; } // 先判断问题,拆成print Circle, // 确定起点和终点的变化(看坐标,起点和终点的坐标相加和相同) // 四个顺序,除了第一个,剩下的都是有条件的,并且要执行后一个必须要满足前面所有的条件。 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]); } } };
转载于:https://www.cnblogs.com/cookcoder-mr/p/11123310.html