Skip to content

Commit d92c799

Browse files
committed
Spiral Matrix
1 parent 5eeaa46 commit d92c799

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

spiral-matrix/TonyKim9401.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public List<Integer> spiralOrder(int[][] matrix) {
3+
List<Integer> output = new ArrayList<>();
4+
int north = 0;
5+
int south = matrix.length - 1;
6+
int east = matrix[0].length - 1;
7+
int west = 0;
8+
9+
while (north <= south && west <= east) {
10+
int j = west;
11+
while (j <= east) {
12+
output.add(matrix[north][j]);
13+
j += 1;
14+
}
15+
north += 1;
16+
17+
int i = north;
18+
while (i <= south) {
19+
output.add(matrix[i][east]);
20+
i += 1;
21+
}
22+
east -= 1;
23+
24+
if (north <= south) {
25+
j = east;
26+
while (j >= west) {
27+
output.add(matrix[south][j]);
28+
j -= 1;
29+
}
30+
south -= 1;
31+
}
32+
33+
if (west <= east) {
34+
i = south;
35+
while (i >= north) {
36+
output.add(matrix[i][west]);
37+
i -= 1;
38+
}
39+
west += 1;
40+
}
41+
}
42+
return output;
43+
}
44+
}

0 commit comments

Comments
 (0)