该题也是老面熟了,还记得蛇形填数吗(我可总结过了)
蛇形填数(总结篇)_ZZZWWWFFF_的博客-CSDN博客
按照之前做过的蛇形填数的思路/模板来做就行(注意边界问题)
在这题我在处理边界所花费的时间还是太长了~~~
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
int x = 0, y = 0,cn=1;
vector<int> ans;
vector<vector<int> > book(n,vector<int>(m,0));//记录是否走过
ans.push_back(matrix[0][0]);
while (cn < n * m)//确保走完全部格子
{
while (y + 1 < m && book[x][y + 1] == 0)
{
cn++;
book[x][y] = 1;
ans.push_back(matrix[x][++y]);
}
while (x + 1 < n && book[x + 1][y] == 0)
{
cn++;
book[x][y] = 1;
ans.push_back(matrix[++x][y]);
}
while (y - 1 >= 0 && book[x][y - 1] == 0)
{
cn++;
book[x][y] = 1;
ans.push_back(matrix[x][--y]);
}
while (x - 1 >= 0 && book[x - 1][y] == 0)
{
cn++;
book[x][y] = 1;
ans.push_back(matrix[--x][y]);
}
}
return ans;
}
};