Advertisement
nikunjsoni

54

Sep 16th, 2021
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> spiralOrder(vector<vector<int>>& m) {
  4.         vector<int> res;
  5.         int rows = m.size(), cols = m[0].size();
  6.         int left=0, right=cols-1, up=0, down=rows-1;
  7.        
  8.         while(res.size() < rows*cols){
  9.             for(int col=left; col<=right; col++)
  10.                 res.push_back(m[up][col]);
  11.            
  12.             for(int row=up+1; row<=down; row++)
  13.                 res.push_back(m[row][right]);
  14.            
  15.             if(up != down){
  16.                 for(int col=right-1; col>=left; col--)
  17.                     res.push_back(m[down][col]);
  18.             }
  19.            
  20.             if(left != right){
  21.                 for(int row=down-1; row>up; row--){
  22.                     res.push_back(m[row][left]);
  23.                 }
  24.             }
  25.             left++; right--; up++; down--;
  26.         }
  27.         return res;
  28.     }
  29. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement