MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / spiralOrder

Function spiralOrder

spiral_matrix_54/solution.go:3–50  ·  view source on GitHub ↗
(matrix [][]int)

Source from the content-addressed store, hash-verified

1package spiral_matrix_54
2
3func spiralOrder(matrix [][]int) []int {
4 seen := make(map[int]bool)
5 spiral := make([]int, 0)
6 seenStep := false
7 dir := "east"
8 var r, c int
9 for !seenStep && !isOutOfBounds(matrix, r, c) {
10 seen[r*10+c] = true
11 spiral = append(spiral, matrix[r][c])
12
13 switch dir {
14 case "north":
15 r--
16 case "east":
17 c++
18 case "south":
19 r++
20 case "west":
21 c--
22 }
23
24 _, seenStep = seen[r*10+c]
25 if isOutOfBounds(matrix, r, c) || seenStep {
26 switch dir {
27 case "north":
28 r++
29 dir = "east"
30 c++
31 case "east":
32 c--
33 dir = "south"
34 r++
35 case "south":
36 r--
37 dir = "west"
38 c--
39 case "west":
40 c++
41 dir = "north"
42 r--
43 }
44 }
45
46 _, seenStep = seen[r*10+c]
47 }
48
49 return spiral
50}
51
52func isOutOfBounds(m [][]int, r, c int) bool {
53 return r < 0 || r >= len(m) ||

Callers 1

Test_spiralOrderFunction · 0.85

Calls 1

isOutOfBoundsFunction · 0.85

Tested by 1

Test_spiralOrderFunction · 0.68