Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- There will be four kind of movement ie. right(d=0),down(d=1),left(d=2) and up(d=3);
- move left to right in up row.
- move from up to down in right column.
- move from left to right in down row.
- move from down to up in left row.
- Total number of movement should be row*col.
- update the up variable when leaving that row,
- update the right variable when leaving that column.
- similarly for all cases.
- */
- class Solution {
- public:
- vector<int> spiralOrder(vector<vector<int>>& matrix) {
- vector <int> ans;
- int row=matrix.size(),col=matrix[0].size();
- int left=0,right=col-1,up=0,down=row-1;
- int count=row*col;
- while(left<=right && up<=down){
- for(int i=left;i<=right && count>0;i++){ans.push_back(matrix[up][i]); count--;}
- up++;
- for(int i=up;i<=down && count>0;i++){ans.push_back(matrix[i][right]); count--;}
- right--;
- for(int i=right;i>=left && count>0;i--){ ans.push_back(matrix[down][i]);count--;}
- down--;
- for(int i=down;i>=up && count>0;i--){ ans.push_back(matrix[i][left]); count--;}
- left++;
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement