Leetcode每日一题 54.螺旋矩阵

54. 螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 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]

提示:

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

以前写过,直接按圈遍历就行。

每次遍历左上角往右下递增一层,右下角往左上角递减一层。注意控制跳出循环的条件,只要x1或y1其中一个大于x2,y2则跳出循环。

比如:[1,2,3,4],[5,6,7,8]   x1,y1从 元素1 跳到元素6   x2,y2从元素8 跳到 元素3,此时已经遍历完成,如果不跳出循环,则会出现重复数据。

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
43
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<int> ans;

int x1 = 0 , y1 = 0;
int x2 = n - 1, y2 = m - 1;

while(true)
{
if(x1 > x2 || y1 > y2)
{
break;
}

if(x1 == x2)
{
for(int i = y1 ; i <= y2 ; i++)ans.push_back(matrix[x1][i]);
break;
}

if(y1 == y2)
{
for(int i = x1 ; i <= x2 ; i++)ans.push_back(matrix[i][y1]);
break;
}

for(int i = y1 ; i < y2 ; i++)ans.push_back(matrix[x1][i]);
for(int i = x1 ; i < x2 ; i++)ans.push_back(matrix[i][y2]);
for(int i = y2 ; i > y1 ; i--)ans.push_back(matrix[x2][i]);
for(int i = x2 ; i > x1 ; i--)ans.push_back(matrix[i][y1]);

x1++;
y1++;
x2--;
y2--;
}

return ans;
}
};

只要确定了边界,这种题就非常好写了。