解题思路:依照图示思路模仿过程进行
-
-
螺旋矩阵
vector<vector<int>> generateMatrix(int n) { // 创立二维矩阵 vector<vector<int>> matrix(n); for (int i = 0; i < matrix.size(); i++) matrix[i].resize(n); // 上下左右 int u = 0; int d = n - 1; int l = 0; int r = n - 1; int num = 1; while (true) { // 上 for (int i = l; i <= r; i++) matrix[u][i] = num++; if (u++ >= d) break; // 右 for (int i = u; i <= d; i++) matrix[i][r] = num++; if (r-- <= l) break; // 下 for (int i = r; i >= l; i--) matrix[d][i] = num++; if (d-- <= u) break; // 左 for (int i = d; i >= u; i--) matrix[i][l] = num++; if (l++ >= r) break; } return matrix; }
-
59. 螺旋矩阵 II
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
// 上下左右
int u = 0;
int d = matrix.size() - 1;
int l = 0;
int r = matrix[0].size() - 1;
int num = 1;
while (true)
{for (int i = l; i <= r; i++)
{res.emplace_back(matrix[u][i]);
}
if(u++ >= d) break;
for (int i = u; i <= d; i++)
{res.emplace_back(matrix[i][r]);
}
if (r-- <= l) break;
for (int i = r; i >= l; i--)
{res.emplace_back(matrix[d][i]);
}
if (d-- <= u) break;
for (int i = d; i >= u; i--)
{res.emplace_back(matrix[i][l]);
}
if (l++ >= r) break;
}
return res;
}