并不涉及什么算法
最简单的螺旋矩阵
54. 螺旋矩阵
剑指 Offer 29. 顺时针打印矩阵
以上两个题目基本相同,但29的测试用例中包含了空矩阵,所以还是要先考虑这种情况。如果矩阵为空,就不能用matrix[0].size()
获取矩阵列数。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
if (m == 0) return {};
int n = matrix[0].size();
vector<vector<bool>> flag(m, vector<bool>(n));
vector<int> ans(m * n);
int x = 0, y = 0, i = 0;
while (i < (m * n)) {
while (y < n && !flag[x][y]) {
ans[i] = matrix[x][y];
flag[x][y] = true;
i++, y++;
}
y--, x++;
while (x < m && !flag[x][y]) {
ans[i] = matrix[x][y];
flag[x][y] = true;
i++, x++;
}
x--, y--;
while (y >= 0 && !flag[x][y]) {
ans[i] = matrix[x][y];
flag[x][y] = true;
i++, y--;
}
y++, x--;
while (x >= 0 && !flag[x][y]) {
ans[i] = matrix[x][y];
flag[x][y] = true;
i++, x--;
}
x++, y++;
}
return ans;
}
};
螺旋矩阵 II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int h = 0, v = 0, x = 0;
vector<vector<bool>> flag(n, vector<bool>(n));
vector<vector<int>> ans(n, vector<int>(n));
vector<int> num;
for (int i = 1; i <= n * n; i++) {
num.push_back(i);
cout << i;
}
while (x < n * n) {
while (v < n && !flag[h][v]) {
ans[h][v] = num[x];
flag[h][v] = true;
x++, v++;
}
v--, h++;
while (h < n && !flag[h][v]) {
ans[h][v] = num[x];
flag[h][v] = true;
x++, h++;
}
h--, v--;
while (v >= 0 && !flag[h][v]) {
ans[h][v] = num[x];
flag[h][v] = true;
x++, v--;
}
v++, h--;
while (h >= 0 && !flag[h][v]) {
ans[h][v] = num[x];
flag[h][v] = true;
x++, h--;
}
h++, v++;
}
return ans;
}
};
螺旋矩阵 III
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int step = 1, cnt = 0;
vector<vector<int>> ans(rows * cols, vector<int>(1, 2));
vector<vector<bool>> flag(rows, vector<bool>(cols));
while (cnt < rows * cols) {
for (int j = 0; j < step; j++) {
if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {
ans[cnt] = {rStart, cStart};
flag[rStart][cStart] = true;
cnt++;
}
cStart++;
}
for (int j = 0; j < step; j++) {
if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {
ans[cnt] = {rStart, cStart};
flag[rStart][cStart] = true;
cnt++;
}
rStart++;
}
step++;
for (int j = 0; j < step; j++) {
if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {
ans[cnt] = {rStart, cStart};
flag[rStart][cStart] = true;
cnt++;
}
cStart--;
}
for (int j = 0; j < step; j++) {
if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols) {
ans[cnt] = {rStart, cStart};
flag[rStart][cStart] = true;
cnt++;
}
rStart--;
}
step++;
}
return ans;
}
};