Leetcode(54) Spiral Matrix

Description

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

1
2
3
4
5
6
7
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

1
2
3
4
5
6
7
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

解法

这题就按照四个方向来进行数组的遍历,注意方向的转换与边界的处理,同时注意处理一行,一列为空的特殊情况。

具体代码如下:

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
if (matrix.length == 0) {
return res;
}
if (matrix[0].length == 1) {
for (int i = 0; i < matrix.length; i++) {
res.add(matrix[i][0]);
}
return res;
}
if (matrix.length == 1) {
for (int i = 0; i < matrix[0].length; i++) {
res.add(matrix[0][i]);
}
return res;
}
int size = matrix[0].length * matrix.length;
int i = 0;
int j = 0;
int upbond = 1;
int downbond = matrix.length - 1;
int leftbond = 0;
int rightbond = matrix[0].length - 1;
int dir = 0;
res.add(matrix[0][0]);
for (int k = 0; k < size - 1; k++) {
switch (dir) {
case 0: {
j++;
res.add(matrix[i][j]);
if (j == rightbond) {
dir = 1;
rightbond--;
}
break;
}
case 1: {
i++;
res.add(matrix[i][j]);
if (i == downbond) {
dir = 2;
downbond--;
}
break;
}
case 2: {
j--;
res.add(matrix[i][j]);
if (j == leftbond) {
dir = 3;
leftbond++;
}
break;
}
case 3: {
i--;
res.add(matrix[i][j]);
if (i == upbond) {
dir = 0;
upbond++;
}
break;
}
}
}
return res;
}
}