avatar

剑指Offer-顺时针打印矩阵

📝题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
 

限制:
· 0 <= matrix.length <= 100
· 0 <= matrix[i].length <= 100


📝思路

拆解成多层(多个“口”字型路径),内层循环按“上边->右边->下边->左边”逐边遍历,注意检查上下边界或左右边界是否已越界,及时终止循环

📝题解

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
28
29
30
31
32
33
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int row = matrix.size();
if (!row) return res;
int col = matrix[0].size();

for (int layer = 0; layer * 2 < row; layer++) {
if (layer*2+1 > row) break;
//遍历“上边”
for (int j = layer; j < col - layer; j++) {
res.push_back(matrix[layer][j]);
}
if (layer*2+1 == row) break;

if (layer*2+1 > col) break;
//遍历“右边”
for (int i = layer+1; i < row - layer; i++) {
res.push_back(matrix[i][col-1-layer]);
}
if (layer*2+1 == col) break;

//遍历“下边”
for (int j = col-layer-2; j >= layer; j--) {
res.push_back(matrix[row-1-layer][j]);
}

//遍历“左边”
for (int i = row-layer-2; i > layer; i--) {
res.push_back(matrix[i][layer]);
}
}
return res;
}
Author:WhiteBeerHouse
Link:https://github.com/WhiteBeerHouse/WhiteBeerHouse.github.io/tree/master/2021/03/06/%E5%89%91%E6%8C%87Offer-%E9%A1%BA%E6%97%B6%E9%92%88%E6%89%93%E5%8D%B0%E7%9F%A9%E9%98%B5/
Copyright Notice:All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.