-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path54.Spiral-Matrix.java
55 lines (46 loc) · 1.16 KB
/
54.Spiral-Matrix.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// https://leetcode.com/problems/spiral-matrix/
//
// algorithms
// Medium (30.45%)
// Total Accepted: 234,074
// Total Submissions: 768,688
// beats 100.0% of java submissions
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<>();
if (matrix == null) {
return res;
}
int m = matrix.length;
if (m == 0) {
return res;
}
int n = matrix[0].length;
int l = 0, r = n - 1, t = 0, b = m - 1;
while (t <= b && l <= r) {
for (int i = l; i <= r; i++) {
res.add(matrix[t][i]);
}
t++;
if (t > b) {
break;
}
for (int i = t; i <= b; i++) {
res.add(matrix[i][r]);
}
r--;
if (r < l) {
break;
}
for (int i = r; i >= l; i--) {
res.add(matrix[b][i]);
}
b--;
for (int i = b; i >= t; i--) {
res.add(matrix[i][l]);
}
l++;
}
return res;
}
}