kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 54. Spiral Matrix

54. Spiral Matrix

Difficulty:: Medium

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]

Solution

Language: Java

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
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return result;
}
int m = matrix.length;
int n = matrix[0].length;
int left = 0, up = 0, right = n - 1, down = m - 1;
while (left <= right && up <= down) {
for (int i = left; i <= right; i++) {
result.add(matrix[up][i]);
}
up++;
for (int i = up; i <= down; i++) {
result.add(matrix[i][right]);
}
right--;
if (up <= down && left <= right) {
for (int i = right; i >= left; i--) {
result.add(matrix[down][i]);
}
down--;

for (int i = down; i >= up; i--) {
result.add(matrix[i][left]);
}
left++;
}
}
return result;
}
}