54. Spiral Matrix

骑猪看日落 2022-08-20 12:05 261阅读 0赞

54. Spiral Matrix

My Submissions

Question

Total Accepted: 52570 Total Submissions: 238571 Difficulty: Medium

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. ]

You should return [1,2,3,6,9,8,7,4,5].

我的代码如下:效率不是很高,注意下面红色部分的判断

  1. <span style="color:#333333;">class Solution {
  2. public:
  3. vector<int> spiralOrder(vector<vector<int>>& matrix) {
  4. vector<int>res;
  5. if(!matrix.size())return res;
  6. int row = matrix.size();
  7. int col = matrix[0].size();
  8. int temp1 = row%2;
  9. if(row==1)return matrix[0];
  10. if(col==1){
  11. for(int i=0;i<row;i++){
  12. res.push_back(matrix[i][0]);
  13. }
  14. return res;
  15. }
  16. spiral(res, matrix, row-1,col-1,0);
  17. return res;
  18. }
  19. void spiral(vector<int>&res, vector<vector<int>>&matrix,int row,int col, int begin){
  20. if(row>0&&col>0){
  21. int curRow = begin;
  22. int curCol = begin;
  23. </span><span style="color:#cc0000;">if(col==begin) {
  24. for(;curRow <= row;curRow++) {
  25. res.push_back(matrix[curRow][begin]);
  26. }
  27. return;
  28. }</span><span style="color:#333333;">
  29. for(;curCol < col;curCol++){
  30. res.push_back(matrix[curRow][curCol]);
  31. }
  32. for(;curRow<row;curRow++){
  33. res.push_back(matrix[curRow][curCol]);
  34. }
  35. for(;curCol>begin;curCol--){
  36. res.push_back(matrix[curRow][curCol]);
  37. }
  38. for(;curRow>begin;curRow--){
  39. res.push_back(matrix[curRow][curCol]);
  40. }
  41. spiral(res, matrix,row-1,col-1,begin+1);
  42. }else {
  43. return;
  44. }
  45. }
  46. };</span>

发表评论

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

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

相关阅读