Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> spiralOrder(vector<vector<int>>& matrix) {
- vector<int>ans;
- if( matrix.empty() ) return ans;
- int n = (int)matrix.size();
- int m = (int)matrix[0].size();
- int rowStart = 0;
- int rowEnd = n-1;
- int colStart = 0;
- int colEnd = m-1;
- while( rowStart <= rowEnd && colStart <= colEnd )
- {
- // go left to right
- for( int i=colStart; i<= colEnd; i++ )
- {
- ans.push_back(matrix[rowStart][i]);
- }
- rowStart++;
- // go top to down
- for( int i=rowStart; i<= rowEnd; i++ )
- {
- ans.push_back(matrix[i][colEnd]);
- }
- colEnd--;
- // go right to left;
- if(rowStart <= rowEnd)
- for( int i=colEnd; i>=colStart; i-- )
- {
- ans.push_back(matrix[rowEnd][i]);
- }
- rowEnd--;
- // go down to top
- if( colEnd >= colStart )
- for( int i=rowEnd; i>= rowStart; i-- )
- {
- ans.push_back(matrix[i][colStart]);
- }
- colStart++;
- }
- return ans;
- }
- };
Add Comment
Please, Sign In to add comment