54.Spiral Matrix¶
Tags: Medium
Array
Links: https://leetcode.com/problems/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]
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
std::ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int m = matrix.size();
if (m == 0) return {};
int n = matrix[0].size();
vector<int> res(m * n);
int row = 0, col = 0;
int cnt = 0;
int direction = 0;
while (cnt < m * n) {
res[cnt++] = matrix[row][col];
matrix[row][col] = INT_MAX;
while (cnt < m * n) {
if (direction == 0) {
if (col + 1 < n && matrix[row][col + 1] != INT_MAX) {
++col; break;
}
else {
direction = (direction + 1) % 4;
}
}
if (direction == 1) {
if (row + 1 < m && matrix[row + 1][col] != INT_MAX) {
++row; break;
}
else
direction = (direction + 1) % 4;
}
if (direction == 2) {
if (col - 1 >= 0 && matrix[row][col - 1] != INT_MAX) {
--col; break;
}
else
direction = (direction + 1) % 4;
}
if (direction == 3) {
if (row - 1 >= 0 && matrix[row - 1][col] != INT_MAX) {
--row; break;
}
else
direction = (direction + 1) % 4;
}
}
}
return res;
}
};
原始矩阵访问过的用INT_MAX
标记,节省了空间。