Skip to content

Commit a98baee

Browse files
committedMay 10, 2025
solve spiral matrix
1 parent 4cbf92f commit a98baee

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
 

‎spiral-matrix/sora0319.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.*;
2+
3+
class SolutionSpiral {
4+
public List<Integer> spiralOrder(int[][] matrix) {
5+
List<Integer> result = new ArrayList<>();
6+
7+
if (matrix == null || matrix.length == 0) return result;
8+
9+
int top = 0, bottom = matrix.length - 1;
10+
int left = 0, right = matrix[0].length - 1;
11+
12+
while (top <= bottom && left <= right) {
13+
// Traverse from left to right
14+
for (int col = left; col <= right; col++) {
15+
result.add(matrix[top][col]);
16+
}
17+
top++;
18+
19+
if (top > bottom) break;
20+
21+
for (int row = top; row <= bottom; row++) {
22+
result.add(matrix[row][right]);
23+
}
24+
right--;
25+
26+
if (left > right) break;
27+
28+
for (int col = right; col >= left; col--) {
29+
result.add(matrix[bottom][col]);
30+
}
31+
bottom--;
32+
33+
for (int row = bottom; row >= top; row--) {
34+
result.add(matrix[row][left]);
35+
}
36+
left++;
37+
}
38+
39+
return result;
40+
}
41+
}
42+

0 commit comments

Comments
 (0)