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+ class Solution {
2+ func spiralOrder( _ matrix: [ [ Int ] ] ) -> [ Int ] {
3+ guard !matrix. isEmpty else { return [ ] }
4+
5+ var answer : [ Int ] = [ ]
6+
7+ var top = 0
8+ var bottom = matrix. count - 1
9+ var left = 0
10+ var right = matrix [ 0 ] . count - 1
11+
12+ while top <= bottom && left <= right {
13+ for i in left... right {
14+ answer. append ( matrix [ top] [ i] )
15+ }
16+ top += 1
17+
18+ if top <= bottom {
19+ for i in top... bottom {
20+ answer. append ( matrix [ i] [ right] )
21+ }
22+ }
23+ right -= 1
24+
25+ if top <= bottom && left <= right {
26+ for i in stride ( from: right, through: left, by: - 1 ) {
27+ answer. append ( matrix [ bottom] [ i] )
28+ }
29+ bottom -= 1
30+ }
31+
32+ if left <= right && top <= bottom {
33+ for i in stride ( from: bottom, through: top, by: - 1 ) {
34+ answer. append ( matrix [ i] [ left] )
35+ }
36+ left += 1
37+ }
38+ }
39+
40+ return answer
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments