-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
80 lines (73 loc) · 1.95 KB
/
SpiralMatrix.java
File metadata and controls
80 lines (73 loc) · 1.95 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
72
73
74
75
76
77
78
79
80
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author eko
*
* Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
*
* Example 1:
*
* Input:
* [
* [ 1, 2, 3 ],
* [ 4, 5, 6 ],
* [ 7, 8, 9 ]
* ]
* Output: [1,2,3,6,9,8,7,4,5]
* Example 2:
*
* 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]
*/
public class SpiralMatrix {
public static void main(String[] args) {
int[][] matrix = new int[3][4];
int n = 1;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = n++;
}
}
System.out.println(spiralOrder(matrix));
}
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int rows = matrix.length;
int cols = matrix[0].length;
int n = 0;
while (rows > 0 && cols > 0) {
if (rows == 1) {
for (int i = 0; i < cols; i++) {
result.add(matrix[n][n+i]);
}
} else if (cols == 1) {
for (int i = 0; i < rows; i++) {
result.add(matrix[n+i][n]);
}
} else {
for (int i = 0; i < cols - 1; i++) {
result.add(matrix[n][n+i]);
}
for (int i = 0; i < rows - 1; i++) {
result.add(matrix[n + i][n + cols - 1]);
}
for (int i = cols - 1; i > 0; i--) {
result.add(matrix[n + rows - 1][n + i]);
}
for (int i = rows - 1; i > 0; i--) {
result.add(matrix[n + i][n]);
}
}
rows -= 2;
cols -= 2;
n++;
}
return result;
}
}