LeetCode54.螺旋矩阵
题解思路
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int n = matrix.size();// 行
int m = matrix[0].size(); // 列
vector<vector<bool>> st(n, vector<bool>(m));
// 方向数组
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
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 x1 = x + dx[d], y1 = y + dy[d];
// 边界判断
if(x1 < 0 || x1 >= n || y1 < 0 || y1 >= m || st[x1][y1]){
// 遇到边界,就改变方向
d = (d + 1) % 4;
x1 = x + dx[d], y1 = y + dy[d];
}
x = x1, y = y1;
}
return res;
}
};