给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m = = m a t r i x . l e n g t h m == matrix.length m==matrix.length
n = = m a t r i x [ i ] . l e n g t h n == matrix[i].length n==matrix[i].length
1 < = m , n < = 10 1 <= m, n <= 10 1<=m,n<=10
− 100 < = m a t r i x [ i ] [ j ] < = 100 -100 <= matrix[i][j] <= 100 −100<=matrix[i][j]<=100
思路:
-
- 将 右、下、左、上 分别映射为 0~3 个方向
-
- 刚开始从 (0, 0) 坐标位置开始出发,从 0 方向(右方向)开始走
-
- 当此时的 坐标越界,或者已经访问过元素,开始转换方向 (t + 1) % 4
-
- 直到遍历的元素等于原数组元素的 个数,则返回
cpp
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
bool st[n][m];
memset(st, 0, sizeof st);
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
int t = 0, cnt = n * m;
vector<int> res;
int x = 0, y = 0;
st[0][0] = true;
res.push_back(matrix[0][0]);
while(res.size() != cnt){
int a = x + dx[t], b = y + dy[t];
if(a < 0 || a >= n || b < 0 || b >= m || st[a][b]){
t = (t + 1) % 4;
continue;
}
x = a, y = b;
st[a][b] = true;
res.push_back(matrix[x][y]);
}
return res;
}
};