File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments