题目描述
给定一个包含 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]
题解
模拟法,模拟螺旋矩阵的填写顺序。
代码
/*
模拟法
时间复杂度为o(m * n)
空间复杂度为o(m * n)
*/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows = matrix.size();
if(rows == 0){
return vector<int>({});
}
int cols = matrix[0].size();
int len = rows * cols, x = 0, y = 0 , idx = 0, next_x, next_y;
int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//指定螺旋方向
vector<int>res(rows * cols, 0);
bool mark[rows][cols];
memset(mark, false, sizeof(mark));//初始化
for(int i = 0; i < len; ++i){
res[i] = matrix[x][y];
mark[x][y] = true;
if(i == len - 1) break;
while(1){
next_x = x + dir[idx][0];
next_y = y + dir[idx][1];
if(next_x < 0 || next_x >= rows || next_y < 0 || next_y >= cols || mark[next_x][next_y]){//越界或者访问过,改变方向
idx = (idx + 1) % 4;
}
else{//找到螺旋的下一个位置,直接跳出
x = next_x;
y = next_y;
break;
}
}
}
return res;
}
};