题目
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
样例
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

解法:模拟

通过while循环去模拟每一圈的打印过程即可
主要是需要通过画图想清楚边界条件
时间复杂度O(n^2),空间复杂度O(1)

  1. class Solution {
  2. public:
  3. vector<int> printMatrix(vector<vector<int> > matrix) {
  4. vector<int> ans;
  5. if (matrix.empty()) return ans;
  6. int hmax = matrix.size() - 1, wmax = matrix[0].size() - 1;
  7. int hmin = 0, wmin = 0;
  8. while (hmin <= hmax && wmin <= wmax) {
  9. // cout << hmin << ' ' << hmax << ' ' << wmin << ' ' << wmax << endl;
  10. print(hmin, hmax, wmin, wmax, matrix, ans);
  11. hmin++, hmax--;
  12. wmin++, wmax--;
  13. }
  14. return ans;
  15. }
  16. void print(int hmin, int hmax, int wmin, int wmax, const vector<vector<int>> matrix, vector<int> &ans) {
  17. for (int i = wmin; i <= wmax; i++) {
  18. ans.push_back(matrix[hmin][i]);
  19. }
  20. for (int i = hmin + 1; i <= hmax; i++) {
  21. ans.push_back(matrix[i][wmax]);
  22. }
  23. if (hmin < hmax) { // 多于1行
  24. for (int i = wmax - 1; i >= wmin; i--) {
  25. ans.push_back(matrix[hmax][i]);
  26. }
  27. }
  28. if (wmin < wmax) { // 多于1列
  29. for (int i = hmax - 1; i > hmin; i--) {
  30. ans.push_back(matrix[i][wmin]);
  31. }
  32. }
  33. }
  34. };