题目:给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例:
1、输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
2、输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
方案一:
class Solution {
vector<vector<int>> delta = {{0,1}, {1,0}, {0,-1}, {-1, 0}};
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int row = matrix.size(), col = matrix[0].size();
int total = row * col;
vector<int> res = vector<int>(total);
vector<vector<int>> status = vector<vector<int>>(row, vector<int>(col, 0));
int m = 0, n = 0;
int direction = 0;
for (int i = 0; i < total; i++) {
res[i] = matrix[m][n];
status[m][n] = 1;
int nextM = m + delta[direction][0];
int nextN = n + delta[direction][1];
// 方向只会变化一次
if (nextM >= 0 && nextM < row && nextN >= 0 && nextN < col && status[nextM][nextN] == 0) {
m = nextM;
n = nextN;
} else {
direction = (direction + 1) % 4;
m += delta[direction][0];
n += delta[direction][1];
}
}
return res;
}
};
时间复杂度
空间复杂度
方案二:按层模拟
可以将矩阵看成若干层,首先输出最外层的元素,其次输出次外层的元素,直到输出最内层的元素。

从左到右遍历上侧元素,依次为 (top, left) 到 (top,right)。
从上到下遍历右侧元素,依次为 (top+1, right) 到 (bottom, right)。
如果 left <right 且 top<bottom,则从右到左遍历下侧元素,依次为 (bottom,right−1) 到 (bottom,left),以及从下到上遍历左侧元素,依次为 (bottom - 1,left) 到 (top+1,left)。
遍历完当前层的元素之后,将 left 和 \top 分别增加 11,将 right 和 bottom 分别减少 11,进入下一层继续遍历,直到遍历完所有元素为止。
class Solution {
private:
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int row = matrix.size();
int col = matrix[0].size();
auto res = vector<int>(row * col);
int top = 0, bottom = row - 1, left = 0, right = col - 1;
int cnt = 0;
while(top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
res[cnt++] = matrix[top][i];
}
for (int j = top+1; j <= bottom; j++) {
res[cnt++] = matrix[j][right];
}
if (bottom > top && right > left) {
for (int i = right - 1; i >= left; i--) {
res[cnt++] = matrix[bottom][i];
}
for (int j = bottom - 1; j > top; j--) {
res[cnt++] = matrix[j][left];
}
}
left++;right--;top++;bottom--;
}
return res;
}
};
时间复杂度
空间复杂度
本文介绍了如何按顺时针螺旋顺序遍历矩阵中的所有元素,提供了两种解决方案。第一种方案详细分析了时间复杂度和空间复杂度。第二种方案通过模拟逐层遍历,从外层至内层,依次处理矩阵的四个边界,直至遍历完整个矩阵,同样给出了时间复杂度和空间复杂度的说明。

914

被折叠的 条评论
为什么被折叠?



