Advertisement
imashutosh51

Spiral Matrix

Oct 6th, 2022 (edited)
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. /*
  2. There will be four kind of movement ie. right(d=0),down(d=1),left(d=2) and up(d=3);
  3. move left to right in up row.
  4. move from up to down in right column.
  5. move from left to right in down row.
  6. move from down to up in left row.
  7.  
  8. Total number of movement should be row*col.
  9. update the up variable when leaving that row,
  10. update the right variable when leaving that column.
  11. similarly for all cases.
  12. */
  13. class Solution {
  14. public:
  15.     vector<int> spiralOrder(vector<vector<int>>& matrix) {
  16.         vector <int> ans;
  17.         int row=matrix.size(),col=matrix[0].size();
  18.         int left=0,right=col-1,up=0,down=row-1;
  19.         int count=row*col;
  20.         while(left<=right && up<=down){
  21.             for(int i=left;i<=right && count>0;i++){ans.push_back(matrix[up][i]); count--;}
  22.             up++;
  23.             for(int i=up;i<=down && count>0;i++){ans.push_back(matrix[i][right]); count--;}
  24.             right--;
  25.             for(int i=right;i>=left && count>0;i--){ ans.push_back(matrix[down][i]);count--;}
  26.             down--;
  27.             for(int i=down;i>=up && count>0;i--){ ans.push_back(matrix[i][left]); count--;}
  28.             left++;
  29.         }
  30.         return ans;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement