先走外面的圈再走里面的圈,可以用递归来解决,对于要走的一个圈,由四个角决定,其实是三个数,(0,0),(0,n),(m,0),(m,n),每次先从左上角走到右上角,再走到右下角,再走到左下角,再走回来
对于后面两个的往回走要在m和n不等于起点的情况下,否则会重复最后
class Solution {
public:
vector<int> ans;
vector<vector<int> > matrix;
void go(int start, int row, int column) {
if (start > row || start > column)
return;
for (int i = start; i <= column; ++i)
ans.push_back(matrix[start][i]);
for (int i = start + 1; i <= row; ++i)
ans.push_back(matrix[i][column]);
if (row != start)
for (int i = column - 1; i >= start; --i)
ans.push_back(matrix[row][i]);
if (column != start)
for (int i = row - 1; i > start; --i)
ans.push_back(matrix[i][start]);
go(start + 1, row - 1, column - 1);
}
vector<int> spiralOrder(vector<vector<int> > &matrix) {
this->matrix = move(matrix);
go(0, this->matrix.size() - 1, this->matrix[0].size() - 1);
return ans;
}
};
不用递归也可以,改成迭代
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ans;
int start = 0, row = matrix.size() - 1, column = matrix[0].size() - 1;
while (true) {
if (start > row || start > column)
break;
for (int i = start; i <= column; ++i)
ans.push_back(matrix[start][i]);
for (int i = start + 1; i <= row; ++i)
ans.push_back(matrix[i][column]);
if (row != start)
for (int i = column - 1; i >= start; --i)
ans.push_back(matrix[row][i]);
if (column != start)
for (int i = row - 1; i > start; --i)
ans.push_back(matrix[i][start]);
++start;
--row;
--column;
}
return ans;
}
};