File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ traverse right and increment rowBegin, then traverse down and decrement colEnd,
3
+ traverse left and decrement rowEnd, and finally I traverse up and increment colBegin.
4
+
5
+ The only tricky part is that when traverse left or up, we have to check whether the
6
+ row or col still exists to prevent duplicates.
7
+ */
8
+ public class Solution {
9
+ public IList < int > SpiralOrder ( int [ , ] matrix ) {
10
+ List < int > res = new List < int > ( ) ;
11
+ if ( matrix . GetLength ( 0 ) == 0 ) {
12
+ return res ;
13
+ }
14
+ int rowBegin = 0 ;
15
+ int rowEnd = matrix . GetLength ( 0 ) - 1 ;
16
+ int colBegin = 0 ;
17
+ int colEnd = matrix . GetLength ( 1 ) - 1 ;
18
+ while ( rowBegin <= rowEnd && colBegin <= colEnd ) {
19
+ // traverse right
20
+ for ( int i = colBegin ; i <= colEnd ; i ++ ) {
21
+ res . Add ( matrix [ rowBegin , i ] ) ;
22
+ }
23
+ rowBegin ++ ;
24
+ // traverse down
25
+ for ( int i = rowBegin ; i <= rowEnd ; i ++ ) {
26
+ res . Add ( matrix [ i , colEnd ] ) ;
27
+ }
28
+ colEnd -- ;
29
+ if ( rowBegin <= rowEnd ) {
30
+ // traverse left
31
+ for ( int i = colEnd ; i >= colBegin ; i -- ) {
32
+ res . Add ( matrix [ rowEnd , i ] ) ;
33
+ }
34
+ }
35
+ rowEnd -- ;
36
+ if ( colBegin <= colEnd ) {
37
+ // traverse up
38
+ for ( int i = rowEnd ; i >= rowBegin ; i -- ) {
39
+ res . Add ( matrix [ i , colBegin ] ) ;
40
+ }
41
+ }
42
+ colBegin ++ ;
43
+ }
44
+ return res ;
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments