# 54. Spiral Matrix

Given an `m x n` `matrix`, return all elements of the `matrix` in spiral order.

Example 1:

``````Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
``````

Example 2:

``````Input: matrix = [[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]
``````

Constraints:

• `m == matrix.length`
• `n == matrix[i].length`
• `1 <= m, n <= 10`
• `-100 <= matrix[i][j] <= 100`

1 2 3

4 5 6

7 8 9

``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<int> res;
int c = m > n ? (n + 1) / 2 : (m + 1) / 2;
int p = m, q = n;
for (int i = 0; i < c; ++i, p -= 2, q -= 2) {
for (int col = i; col < i + q; ++col)
res.push_back(matrix[i][col]);
for (int row = i + 1; row < i + p; ++row)
res.push_back(matrix[row][i + q - 1]);
if (p == 1 || q == 1) break;
for (int col = i + q - 2; col >= i; --col)
res.push_back(matrix[i + p - 1][col]);
for (int row = i + p - 2; row > i; --row)
res.push_back(matrix[row][i]);
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<int> res;
int up = 0, down = m - 1, left = 0, right = n - 1;
while (true) {
for (int j = left; j <= right; ++j) res.push_back(matrix[up][j]);
if (++up > down) break;
for (int i = up; i <= down; ++i) res.push_back(matrix[i][right]);
if (--right < left) break;
for (int j = right; j >= left; --j) res.push_back(matrix[down][j]);
if (--down < up) break;
for (int i = down; i >= up; --i) res.push_back(matrix[i][left]);
if (++left > right) break;
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size(), idx = 0, i = 0, j = 0;
vector<int> res;
vector<vector<int>> visited(m, vector<int>(n));
vector<vector<int>> dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
for (int k = 0; k < m * n; ++k) {
res.push_back(matrix[i][j]);
visited[i][j] = 1;
int x = i + dirs[idx][0], y = j + dirs[idx][1];
if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y] == 1) {
idx = (idx + 1) % 4;
x = i + dirs[idx][0];
y = j + dirs[idx][1];
}
i = x;
j = y;
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/54

Spiral Matrix II

Spiral Matrix IV

https://leetcode.com/problems/spiral-matrix/

https://leetcode.com/problems/spiral-matrix/discuss/20719/0ms-Clear-C%2B%2B-Solution

https://leetcode.com/problems/spiral-matrix/discuss/20599/Super-Simple-and-Easy-to-Understand-Solution

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation