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].
方法1:递归,复杂方式。
class Solution {
private:
// up left..... down right
void traverse(vector<int>& res, int ul_x, int ul_y, int dr_x, int dr_y, vector<vector<int>>& matrix) {
if (dr_x < ul_x || dr_y < ul_y)
return;
if (dr_x == ul_x) {
for (int i = ul_y; i <= dr_y; ++i) {
res.push_back(matrix[i][dr_x]);
}
return;
}
if (dr_y == ul_y) {
for (int j = ul_x; j <= dr_x; ++j)
res.push_back(matrix[dr_y][j]);
return;
}
for (int j = ul_x; j <= dr_x; ++j)
res.push_back(matrix[ul_y][j]);
for (int i = ul_y + 1; i <= dr_y; ++i)
res.push_back(matrix[i][dr_x]);
for (int j = dr_x - 1; j >= ul_x; --j)
res.push_back(matrix[dr_y][j]);
for (int i = dr_y - 1; i >= ul_y + 1; --i)
res.push_back(matrix[i][ul_x]);
traverse(res, ul_x + 1, ul_y + 1, dr_x - 1, dr_y - 1, matrix);
}
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.size() == 0)
return res;
traverse(res, 0, 0, matrix[0].size() - 1, matrix.size()-1, matrix);
return res;
}
};
方法2:记录步长方式
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.empty())
return res;
int m = matrix.size();
int n = matrix[0].size();
int i = 0;
int k;
int x = 0,y = -1;
const int move_x[]={0,1,0,-1};
const int move_y[]={1,0,-1,0};
while(m>0&&n>0){
if(i%2==0){
k=n;
m--;
}
else{
k=m;
n--;
}
while(k--){
x+=move_x[i];
y+=move_y[i];
res.push_back(matrix[x][y]);
}
i=(i+1)%4;
}
return res;
}
};