54. Spiral Matrix
问题描述
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
思路分析
给一二维数组,将它里面的元素逆时针螺旋输出。
设计一个二维数组dirs,保存了四个方向的操作,起始位置为(0, -1),用一个d符号为表示现在指针运行的方向,m为行数,n为列数,计算出总的循环次数i次。
首先开始在第一行逐列输出,然后在到达n-1位置后循环结束,互换行列,开始在最后一列逐行输出,此时n已经是m值了,要去掉一行已遍历的部分。然后是改变方向,用模除即可。
代码
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.size() == 0)
return res;
int m = matrix.size();
int n = matrix[0].size();
int d = 0;
int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int pos[2] = {0, -1};
int i = m * n;
while (i > 0){
for (int j = 0; j < n; j++){
i--;
pos[0] += dirs[d][0];
pos[1] += dirs[d][1];
res.push_back(matrix[pos[0]][pos[1]]);
}
swap(m, n);
n--;
d = (d + 1) % 4;
}
return res;
}
};
时间复杂度:
空间复杂度:
反思
在游戏开发中,要用dirs数组保存运动方向。可以通过直接输入matrix第一行进入res提高一定的效率。