Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> spiralOrder(vector<vector<int>>& matrix) {
- int m=matrix.size();
- vector<int> result;
- if(m==0)
- return result;
- if(m==1)
- return matrix.front();
- int n=matrix.front().size();
- int up=0,left=0,down=m,right=n;
- int direction=1;
- int i=0;
- int j=0;
- while(up!=down&&left!=right)
- {
- result.push_back(matrix[i][j]);
- if(direction==1)//left
- {
- if(j+1<right)
- {
- j++;
- }
- else
- {
- up++;
- i++;
- direction=2;
- }
- }
- else if(direction==2)//down
- {
- if(i+1<down)
- {
- ++i;
- }
- else
- {
- right--;
- --j;
- direction=3;
- }
- }
- else if(direction==3)//left
- {
- if(j>left)
- {
- --j;
- }
- else
- {
- --down;
- --i;
- direction=0;
- }
- }
- else//up
- {
- if(i>up)
- {
- --i;
- }
- else
- {
- ++j;
- left++;
- direction=1;
- }
- }
- }
- return result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement