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]
.
另一种方法我觉得比较好,是就像rotate 90°那样一圈一圈来,从外到里,不需要额外的空间。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> res;
int rows = matrix.size();
if(rows ==0) return res;
int cols = matrix[0].size();
vector<vector<bool> > visit(rows + 2, vector<bool>(cols + 2,false));
for(int i = 0; i< rows +2; ++i){
visit[i][0] = true;
visit[i][cols + 1] = true;
}
for(int i = 0; i< cols +2; ++i){
visit[0][i] = true;
visit[rows + 1][i] = true;
}
int count = rows * cols;
int pos_x = 0;
int pos_y = 0;
int step_x = 0;
int step_y = 1;
while(count){
res.push_back(matrix[pos_x][pos_y]);
visit[pos_x+1][pos_y+1] = true;
int next_x = pos_x + step_x;
int next_y = pos_y + step_y;
if(visit[next_x + 1][next_y + 1] == true){
if(step_x){
step_y = step_y - step_x;
step_x = 0;
}
else{
step_x = step_y - step_x;
step_y =0;
}
next_x = pos_x + step_x;
next_y = pos_y + step_y;
}
pos_x = next_x;
pos_y = next_y;
count--;
}
return res;
}
};