链接
https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
耗时
解题:38 min 题解:10 min
题意
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
思路
将矩阵的每一圈作为一个循环节,问题即变为按从外到内的顺序顺时针输出矩阵每一圈的数字。一圈顺时针读取又可拆分为 4 部分,以最左上角的数字为起点,从左到右,从上到下,从右到左,从下到上。
PS: 特殊情况有一圈只有一行或一列,矩阵为空。
AC代码
class Solution {
public:
void solve(int x
, int y
, int xs
, int xt
, int ys
, int yt
, vector
<vector
<int>>& matrix
, vector
<int> &ans
) {
ans
.push_back(matrix
[x
][y
]);
while(++y
< yt
) {
ans
.push_back(matrix
[x
][y
]);
}
if(xt
-xs
== 1) return ;
y
= yt
-1;
while(++x
< xt
) {
ans
.push_back(matrix
[x
][y
]);
}
if(yt
-ys
== 1) return ;
x
= xt
-1;
while(--y
>= ys
) {
ans
.push_back(matrix
[x
][y
]);
}
y
= ys
;
while(--x
> xs
) {
ans
.push_back(matrix
[x
][y
]);
}
}
vector
<int> spiralOrder(vector
<vector
<int>>& matrix
) {
if(matrix
.empty()) return {};
vector
<int> ans
;
int n
= matrix
.size();
int m
= matrix
[0].size();
for(int i
= 0, j
= 0; i
< (n
+1)/2 && j
< (m
+1)/2; ++i
, ++j
) {
solve(i
, j
, i
, n
-i
, j
, m
-j
, matrix
, ans
);
}
return ans
;
}
};