题目描述

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
130 螺旋矩阵 - 图1

解题思路

按照剥洋葱的方法进行遍历,即

  1. ->->->
  2. ^ |
  3. | v
  4. ^ |
  5. | v
  6. <-<-<-
  1. class Solution {
  2. public:
  3. vector<int> ret;
  4. void outer_iter(vector<vector<int>>& matrix, int x, int y, int width, int height) {
  5. if (x == matrix.size() || y == matrix[0].size() || width <= 0 || height <= 0)
  6. return;
  7. // 上
  8. for (int j=y; j<=y+width-1; j++) {
  9. ret.push_back(matrix[x][j]);
  10. }
  11. // 右
  12. for (int i=x+1; i<x+height-1; i++) {
  13. ret.push_back(matrix[i][y+width-1]);
  14. }
  15. if (height > 1) {
  16. // 下
  17. for (int j=y+width-1; j>=y; j--) {
  18. ret.push_back(matrix[x+height-1][j]);
  19. }
  20. }
  21. //左
  22. if (width > 1) {
  23. for (int i=x+height-2; i>x; i--) {
  24. ret.push_back(matrix[i][y]);
  25. }
  26. }
  27. outer_iter(matrix, x+1, y+1, width-2, height-2);
  28. }
  29. vector<int> spiralOrder(vector<vector<int>>& matrix) {
  30. outer_iter(matrix, 0, 0, matrix[0].size(), matrix.size());
  31. return ret;
  32. }
  33. };