-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
71 lines (58 loc) · 1.85 KB
/
Copy pathSpiralMatrix.java
File metadata and controls
71 lines (58 loc) · 1.85 KB
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
71
// Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
// See: https://leetcode.com/problems/spiral-matrix/
package leetcode.array_and_hashtable;
import java.util.LinkedList;
import java.util.List;
public class SpiralMatrix {
private final int val = Integer.MIN_VALUE;
public List<Integer> spiralOrder(int[][] M) {
List<Integer> ans = new LinkedList<>();
if (M == null || M.length == 0)
return ans;
int i = 0, j = 0;
while (ans.size() < M.length * M[0].length) {
while (j < M[0].length) {
if (M[i][j] == val)
break;
ans.add(M[i][j]);
M[i][j++] = val;
}
i++; j--;
while (i < M.length) {
if (M[i][j] == val)
break;
ans.add(M[i][j]);
M[i++][j] = val;
}
i--; j--;
while (j >= 0) {
if (M[i][j] == val)
break;
ans.add(M[i][j]);
M[i][j--] = val;
}
i--; j++;
while (i >= 0) {
if (M[i][j] == val)
break;
ans.add(M[i][j]);
M[i--][j] = val;
}
i++; j++;
}
return ans;
}
public static void main(String[] args) {
SpiralMatrix sln = new SpiralMatrix();
System.out.println(sln.spiralOrder(new int[][] {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
}));
System.out.println(sln.spiralOrder(new int[][] {
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12 },
}));
}
}