File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(m*n) m = number of rows, n = number of cols
2+ // Space Complexity: O(m*n)
3+
4+ var spiralOrder = function ( matrix ) {
5+ let result = [ ] ;
6+
7+ while ( matrix . length > 0 ) {
8+ // add the first row to the result
9+ result = result . concat ( matrix . shift ( ) ) ;
10+
11+ // add the last element of each remaining row to the result
12+ for ( let i = 0 ; i < matrix . length ; i ++ ) {
13+ if ( matrix [ i ] . length > 0 ) {
14+ result . push ( matrix [ i ] . pop ( ) ) ;
15+ }
16+ }
17+
18+ // add the last row in reverse order to the result, if any rows are left
19+ if ( matrix . length > 0 ) {
20+ result = result . concat ( matrix . pop ( ) . reverse ( ) ) ;
21+ }
22+
23+ // add the first element of each remaining row to the result in reverse order
24+ for ( let i = matrix . length - 1 ; i >= 0 ; i -- ) {
25+ if ( matrix [ i ] . length > 0 ) {
26+ result . push ( matrix [ i ] . shift ( ) ) ;
27+ }
28+ }
29+ }
30+
31+ // return the result array containing the elements in spiral order
32+ return result ;
33+ } ;
You can’t perform that action at this time.
0 commit comments