knakul853

Untitled

Jun 11th, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> spiralOrder(vector<vector<int>>& matrix) {
  4.        
  5.         vector<int>ans;
  6.         if( matrix.empty() ) return ans;
  7.        
  8.         int n = (int)matrix.size();
  9.         int m = (int)matrix[0].size();
  10.        
  11.         int rowStart = 0;
  12.         int rowEnd = n-1;
  13.        
  14.         int colStart = 0;
  15.         int colEnd = m-1;
  16.        
  17.         while( rowStart <= rowEnd &&  colStart <= colEnd )
  18.         {
  19.             // go left to right
  20.            
  21.             for( int i=colStart; i<= colEnd; i++ )
  22.             {
  23.                 ans.push_back(matrix[rowStart][i]);
  24.                
  25.             }
  26.             rowStart++;
  27.            
  28.             // go top to down
  29.               for( int i=rowStart; i<= rowEnd; i++ )
  30.             {
  31.                 ans.push_back(matrix[i][colEnd]);
  32.                
  33.             }
  34.             colEnd--;
  35.            
  36.             // go right to left;
  37.             if(rowStart <= rowEnd)
  38.               for( int i=colEnd; i>=colStart; i-- )
  39.             {
  40.                 ans.push_back(matrix[rowEnd][i]);
  41.                
  42.             }
  43.             rowEnd--;
  44.            
  45.             // go down to top
  46.             if( colEnd >= colStart )
  47.               for( int i=rowEnd; i>= rowStart; i-- )
  48.             {
  49.                 ans.push_back(matrix[i][colStart]);
  50.                
  51.             }
  52.             colStart++;
  53.         }
  54.        
  55.         return ans;
  56.        
  57.     }
  58. };
Add Comment
Please, Sign In to add comment