Skip to content

Commit 2a6e405

Browse files
authored
Merge pull request neetcode-gh#168 from r1cky0/patch-14
Create 54-Spiral-Matrix.java
2 parents 8f8fbbb + a94e912 commit 2a6e405

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

java/54-Spiral-Matrix.java

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

0 commit comments

Comments
 (0)