avatar

目录
Leetcode 54 螺旋矩阵I

Leetcode 54:螺旋矩阵I

KNGU____O__DPNOF73UAL21.png

整体思路是按题目要求模拟,顺时针转,先从左到右,再从上到下
最后从右到左,从下到上,注意点在于边界值控制

Code
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
34
35
36
37
38
39
40
41
42
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty() || matrix[0].empty())
{
return {};
}
int m = matrix.size();
int n = matrix[0].size();

int up = 0,left = 0;
int down = m-1,right = n-1;

ventor<int> res;

while(up<=down && left<=right)
{
for(int i = left;i <= right;i++) // 注意<= [left,right]
{
res.push_back(matrix[up][i]);
}
for(int i = up + 1;i <= down;i++) //注意+1 <= (up,down]
{
res.push_back(matrix[i][right]);
}
if(up<down && left<right)
//当up==down的时候我们实际上只有一行要输出,上面已经输出了
{
for(int i = right - 1;i > left;i--) //[right,left)
{
res.push_back(matrix[down][i]);
}
for(int i = down;i > up;i--) //(down,up)
{
res.push_back(matrix[i][left]);
}
}
}
return res;
}

};
文章作者: Bellium
文章链接: https://belliumtang.github.io/2020/03/03/Leetcode-54-%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5I/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Bellium
打赏
  • 微信Wechatpay
    微信Wechatpay
  • 支付宝Alipay
    支付宝Alipay