问题
RT
算法:模拟
经典题。关在在于模拟四个方向、确定方向变换的条件(走到不能走了)、遍历的终点(从0到m*n)
复杂度
时间:O(NM)
空间:O(NM)
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int i = 0, j = 0;
int m = matrix.size();
if(!m) return {};
int n = matrix[0].size();
vector<int> ans;
int d = 1;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
vector<vector<bool>> vis(m, vector<bool>(n));
for(int k = 0; k < m*n; k ++){
vis[i][j] = true;
ans.push_back(matrix[i][j]);
int x = i + dx[d], y = j + dy[d];
if(x < 0 || x >= m || y < 0 || y >= n || vis[x][y]){
d = (d+1)%4;
x = i + dx[d], y = j+dy[d];
}
i = x, j = y;
}
return ans;
}
};