【leetcode】54. Spiral Matrix(螺旋矩阵
2019-05-11 本文已影响0人
邓泽军_3679
1、题目描述
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]
2、问题描述:
- 螺旋的打印矩阵。
3、问题关键:
通用的经典做法:
1.定义方向:dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, 1, 0};
2.坐标移动:int a = x + dx[d], b = y + dy[d];
3.边界条件:
if (a < 0 || a == n || b < 0 || b == m || st[a][b]) {
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
4、C++代码:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return vector<int> ();
int n = matrix.size(), m = matrix[0].size();
vector<vector<bool>> f(n, vector<bool>(m, false));
int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};//向右y + 1,向下x + 1, 向左y — 1,向上x - 1.
vector<int> res;
int x = 0, y = 0, d = 0;
for (int i = 0; i < m * n; i ++) {
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || f[a][b]){
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
res.push_back(matrix[x][y]);
f[x][y] = true;
x = a, y = b;
}
return res;
}
};