54.螺旋矩阵
# 54.螺旋矩阵
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
- 解题关键在于控制四个方向遍历时的边界条件,向右遍历到右边界时,矩阵上边界要加1;向下遍历到下边界时,右边界要减1;向左遍历到左边界时,下边界要减1;向上遍历到上边界时,左边界要加1。另一种写法是每次遍历一层,每次处理完一层后四个方向的边界要修改,这里要注意的是最后一层只有一列或者一行的情况。
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res=new ArrayList<>();
int top=0,bottom=matrix.length-1,left=0,right=matrix[0].length-1;
while(top<=bottom&&left<=right)
{
if(left<=right)
{
for(int i=left;i<=right;i++)
res.add(matrix[top][i]);
top++;
}
if(top<=bottom)
{
for(int i=top;i<=bottom;i++)
res.add(matrix[i][right]);
right--;
}
if(left<=right&&top<=bottom) //这里要注意限定条件,处理一行的情况
{
for(int i=right;i>=left;i--)
res.add(matrix[bottom][i]);
bottom--;
}
if(top<=bottom&&left<=right) //处理一列的情况
{
for(int i=bottom;i>=top;i--)
res.add(matrix[i][left]);
left++;
}
}
return res;
}
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
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
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57