这类题,都是纯模拟题,定义一个方向数组,然后一个变量d表示当前在哪个方向上
LeetCode 54.螺旋矩阵 I
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (!matrix.size() || !matrix[0].size()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<int> res;
vector<vector<bool>> st(m, vector<bool>(n, false));
int x = 0, y = 0, d = 0;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
for (int i = 0; i < m * n; i ++) {
res.push_back(matrix[x][y]);
st[x][y] = true;
// 看下一个点是否可行
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= m || b < 0 || b >= n || st[a][b]) d = (d + 1) % 4;
x += dx[d];
y += dy[d];
}
return res;
}
};
LeetCode 59.螺旋矩阵 II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
int x = 0, y = 0, d = 0;
for (int i = 1; i <= n * n; i ++) {
res[x][y] = i;
// 下一个点是否可行
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= n || !res[a][b]) {
d = (d + 1) % 4;
}
x += dx[d];
y += dy[d];
}
return res;
}
};
LeetCode 885.螺旋矩阵 III
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
int tot = R * C;
int cnt = 1;
int x = r0, y = c0, d = 0;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
vector<vector<int>> res;
if (x >= 0 && x < R && y >= 0 && y < C) {
res.push_back({x, y});
tot --;
}
// 步长:1 1 2 2 3 3...
while(tot) {
int len = (cnt - 1) / 2 + 1;
for (int i = 1; i <= len; i ++) {
x += dx[d];
y += dy[d];
// 若在范围内,就加到res
if (x >= 0 && x < R && y >= 0 && y < C) {
res.push_back({x, y});
tot --;
}
}
// 走完步长后,改变方向
d = (d + 1) % 4;
cnt ++;
}
return res;
}
};