Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
//vector<vector<int>> dirs={{0,1},{1,0},{0,-1},{-1,0}};报错,不能有等号
vector<vector<int>> dirs{{0,1},{1,0},{0,-1},{-1,0}};
int nr=matrix.size(); if(nr==0)return res;
int nc=matrix[0].size(); if(nc==0)return res;
//vector<int> nstep={nc,nr-1};报错,不能有等号
//vector<int> nstep{nr,nc-1};报错,nc与nr写反了
vector<int> nstep{nc,nr-1};
int dir=0;
int xr=0,xy=-1;
while(nstep[dir%2]){
for(int i=0;i<nstep[dir%2];++i){
xr+=dirs[dir][0];xy+=dirs[dir][1];
res.push_back(matrix[xr][xy]);
}
nstep[dir%2]--;
dir++;
dir=dir%4;
}
return res;
}
};