给你一个 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 == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
转向数组
根据已知结果集中存储数据个数进行循环遍历。
1、首先,根据每次转弯的行列索引变化总结转向矩阵;
vector<vector<int>> turnVec{``{0,1},{1,0},{0,-1},{-1,0}};//向右、向下、向左、向上
2、其次,根据边界和是否访问过作为约束条件,控制转向;
3、最后,直至结果集元素个数达到上限,即遍历结束。
cpp
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
vector<int> ans;
vector<vector<int>> turnVec{{0,1},{1,0},{0,-1},{-1,0}};//向右、向下、向左、向上
int i = 0,j = 0;
int turn = 0;
int next_i,next_j;
while(ans.size()<rows*cols){
ans.push_back(matrix[i][j]);
matrix[i][j] = 101;//指定矩阵中存储的最大元素值为100
next_i = i + turnVec[turn % 4][0];//按照四个方向的顺序进行转弯
next_j = j + turnVec[turn % 4][1];
//判断是否需要转弯
if(next_i>=rows||next_j>=cols||next_j<0||matrix[next_i][next_j]==101){
++turn;
next_i = i + turnVec[turn % 4][0];
next_j = j + turnVec[turn % 4][1];
}
i = next_i;
j = next_j;
}
return ans;
}
};