1
- func spiralOrder (matrix [][]int ) []int {
1
+ func spiralOrder (matrix [][]int ) ( ans []int ) {
2
2
m , n := len (matrix ), len (matrix [0 ])
3
- ans := make ([]int , 0 , m * n )
4
-
5
- top , bottom , left , right := 0 , m - 1 , 0 , n - 1
6
- for left <= right && top <= bottom {
7
- for i := left ; i <= right ; i ++ {
8
- ans = append (ans , matrix [top ][i ])
9
- }
10
- for i := top + 1 ; i <= bottom ; i ++ {
11
- ans = append (ans , matrix [i ][right ])
12
- }
13
- if left < right && top < bottom {
14
- for i := right - 1 ; i >= left ; i -- {
15
- ans = append (ans , matrix [bottom ][i ])
16
- }
17
- for i := bottom - 1 ; i > top ; i -- {
18
- ans = append (ans , matrix [i ][left ])
19
- }
3
+ vis := make ([][]bool , m )
4
+ for i := range vis {
5
+ vis [i ] = make ([]bool , n )
6
+ }
7
+ dirs := [5 ]int {0 , 1 , 0 , - 1 , 0 }
8
+ i , j , k := 0 , 0 , 0
9
+ for h := m * n ; h > 0 ; h -- {
10
+ ans = append (ans , matrix [i ][j ])
11
+ vis [i ][j ] = true
12
+ x , y := i + dirs [k ], j + dirs [k + 1 ]
13
+ if x < 0 || x >= m || y < 0 || y >= n || vis [x ][y ] {
14
+ k = (k + 1 ) % 4
20
15
}
21
- top ++
22
- bottom --
23
- left ++
24
- right --
16
+ i , j = i + dirs [k ], j + dirs [k + 1 ]
25
17
}
26
-
27
- return ans
28
- }
18
+ return
19
+ }
0 commit comments