方向数组 dx
, dy
什么时候改变方向
越界
- 已经
访问
过 ->bool
数组来辅助判断
class Solution {
public:
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0 , -1 ,0};
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> res;
int n = matrix.size(), m = matrix[0].size();
if(!n || !m) return res; // 特判下
vector<vector<bool>> st(n, vector<bool>(m, false));
for(int i = 0, x = 0, y = 0, d = 0; i < n * m; i ++)
{
res.push_back(matrix[x][y]);
st[x][y] = true;
int nx = x + dx[d], ny = y + dy[d];
if(nx < 0 || nx >= n || ny < 0 || ny >= m ||st[nx][ny])
{
d = (d + 1) % 4;
nx = x + dx[d], ny = y + dy[d];
}
x = nx, y = ny;
}
return res;
}
};