File tree Expand file tree Collapse file tree 1 file changed +27
-59
lines changed Expand file tree Collapse file tree 1 file changed +27
-59
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public List <Integer > spiralOrder (int [][] matrix ) {
3
- List <Integer > list = new ArrayList <>();
4
-
5
- if (matrix .length == 0 || matrix [0 ].length == 0 ) {
6
- return list ;
2
+ public List <Integer > spiralOrder (int [][] matrix ) {
3
+ List <Integer > list = new ArrayList <>();
4
+ int rowStart = 0 ;
5
+ int rowEnd = matrix .length - 1 ;
6
+ int colStart = 0 ;
7
+ int colEnd = matrix [0 ].length - 1 ;
8
+ while (rowStart <= rowEnd && colStart <= colEnd ) {
9
+ for (int i = colStart ; i <= colEnd ; i ++) {
10
+ list .add (matrix [rowStart ][i ]);
11
+ }
12
+ rowStart ++;
13
+ for (int i = rowStart ; i <= rowEnd ; i ++) {
14
+ list .add (matrix [i ][colEnd ]);
15
+ }
16
+ colEnd --;
17
+ if (rowStart <= rowEnd ) {
18
+ for (int i = colEnd ; i >= colStart ; i --) {
19
+ list .add (matrix [rowEnd ][i ]);
7
20
}
8
-
9
- int i = 0 ;
10
- int j = 0 ;
11
- int top = 0 ;
12
- int bottom = matrix .length ;
13
- int left = 0 ;
14
- int right = matrix [0 ].length ;
15
- int dir = 0 ;
16
- int count = 0 ;
17
- int limit = matrix .length * matrix [0 ].length ;
18
-
19
- while (count < limit ) {
20
- if (dir == 0 ) {
21
- while (j < right ) {
22
- list .add (matrix [i ][j ++]);
23
- count ++;
24
- }
25
- dir ++;
26
- right --;
27
- i ++;
28
- j --;
29
- }
30
- else if (dir == 1 ) {
31
- while (i < bottom ) {
32
- list .add (matrix [i ++][j ]);
33
- count ++;
34
- }
35
- dir ++;
36
- bottom --;
37
- i --;
38
- j --;
39
- }
40
- else if (dir == 2 ) {
41
- while (j >= left ) {
42
- list .add (matrix [i ][j --]);
43
- count ++;
44
- }
45
- dir ++;
46
- i --;
47
- j ++;
48
- left ++;
49
- }
50
- else if (dir == 3 ) {
51
- while (i > top ) {
52
- list .add (matrix [i --][j ]);
53
- count ++;
54
- }
55
- dir = 0 ;
56
- top ++;
57
- i ++;
58
- j ++;
59
- }
21
+ rowEnd --;
22
+ }
23
+ if (colStart <= colEnd ) {
24
+ for (int i = rowEnd ; i >= rowStart ; i --) {
25
+ list .add (matrix [i ][colStart ]);
60
26
}
61
-
62
- return list ;
27
+ colStart ++;
28
+ }
63
29
}
30
+ return list ;
31
+ }
64
32
}
You can’t perform that action at this time.
0 commit comments