leetcode 54. Spiral Matrix

雨点打透心脏的1/2处 2022-08-21 04:25 286阅读 0赞

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

  1. [
  2. [ 1, 2, 3 ],
  3. [ 4, 5, 6 ],
  4. [ 7, 8, 9 ]
  5. ]
  6. class Solution {
  7. public:
  8. vector<int> spiralOrder(vector<vector<int>>& matrix) {
  9. vector<int>re;
  10. if (matrix.empty() || matrix[0].empty())
  11. return re;
  12. if (matrix.size() == 1)
  13. {
  14. for (int i = 0; i < matrix[0].size(); i++)
  15. re.push_back(matrix[0][i]);
  16. return re;
  17. }
  18. if (matrix[0].size() == 1)
  19. {
  20. for (int i = 0; i < matrix.size(); i++)
  21. re.push_back(matrix[i][0]);
  22. return re;
  23. }
  24. int row = matrix.size();
  25. int col = matrix[0].size();
  26. int k = 0;
  27. int off = 0;
  28. while (true)
  29. {
  30. for (int i = off; i < col - off; i++)
  31. {
  32. re.push_back(matrix[off][i]); k++;
  33. }
  34. if (k == row*col )
  35. return re;
  36. for (int i = off + 1; i < row - off; i++)
  37. {
  38. re.push_back(matrix[i][col - 1 - off]); k++;
  39. }
  40. if (k == row*col)
  41. return re;
  42. for (int i = col - 2 - off; i >= off; i--)
  43. {
  44. re.push_back(matrix[row - 1 - off][i]); k++;
  45. }
  46. if (k == row*col)
  47. return re;
  48. for (int i = row - 2 - off; i >= off + 1; i--)
  49. {
  50. re.push_back(matrix[i][off]); k++;
  51. }
  52. if (k == row*col)
  53. return re;
  54. off++;
  55. }
  56. }
  57. };

accepted

发表评论

表情:
评论列表 (有 0 条评论,286人围观)

还没有评论,来说两句吧...

相关阅读