题目描述
给定一个包含 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]
算法1
(模拟) $O(mn)$
有4个方向,一旦越界或者已经访问过了,就转弯,直到访问完整个矩阵。
时间复杂度
遍历矩阵一次,复杂度为$O(mn)$
参考文献
C++ 代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty() || matrix[0].empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<vector<bool>> st(m, vector<bool>(n));
vector<int> dr = {0, 1, 0, -1}, dc = {1, 0, -1, 0};
vector<int> res;
for (int r = 0, c = 0, d = 0, num = 1; num <= m * n; ++num){
res.push_back(matrix[r][c]); st[r][c] = true;
int nr = r + dr[d], nc = c + dc[d];
if (nr < 0 || nr >= m || nc < 0 || nc >= n || st[nr][nc]){
d = (d + 1) % 4;
nr = r + dr[d], nc = c + dc[d];
}
r = nr, c = nc;
}
return res;
}
};