题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/

题解

模拟

上下左右指针作为边界,遍历打印。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) return {};
int left = 0, right = matrix[0].size() - 1, top = 0, bottom = matrix.size() - 1;
vector<int> res;
while (true) {
// left to right
for (int i = left; i <= right; ++i)
res.push_back(matrix[top][i]);
if (++top > bottom) break;
// top to bottom
for (int i = top; i <= bottom; ++i)
res.push_back(matrix[i][right]);
if (--right < left) break;
// right to left
for (int i = right; i >= left; --i)
res.push_back(matrix[bottom][i]);
if (--bottom < top) break;
// bottom to top
for (int i = bottom; i >= top; --i)
res.push_back(matrix[i][left]);
if (++left > right) break;
}
return res;
}
};

时间复杂度 O(mn), 空间复杂度 O(1)