-
Notifications
You must be signed in to change notification settings - Fork 0
/
54.spiral-matrix.go
68 lines (61 loc) · 1.25 KB
/
54.spiral-matrix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package solutions
/*
* @lc app=leetcode id=54 lang=golang
*
* [54] Spiral Matrix
*/
/*
Your runtime beats 57.99 % of golang submissions
Your memory usage beats 61.07 % of golang submissions (2 MB)
*/
// @lc code=start
func spiralOrder(matrix [][]int) []int {
topBound := 0
rightBound := len(matrix[0]) - 1
bottomBound := len(matrix) - 1
leftBound := 0
max := len(matrix[0]) * len(matrix)
direction := 0
x := 0
y := 0
path := make([]int, 0)
path = append(path, matrix[y][x])
for len(path) < max {
// fmt.Printf("x=%v, y=%v, dir=%v, %v, %v, %v, %v\n", x, y, direction, rightBound, bottomBound, leftBound, topBound)
if direction == 0 {
if x != rightBound {
x += 1
path = append(path, matrix[y][x])
} else {
direction = 1
topBound++
}
} else if direction == 1 {
if y != bottomBound {
y += 1
path = append(path, matrix[y][x])
} else {
direction = 2
rightBound--
}
} else if direction == 2 {
if x != leftBound {
x -= 1
path = append(path, matrix[y][x])
} else {
direction = 3
bottomBound--
}
} else if direction == 3 {
if y != topBound {
y -= 1
path = append(path, matrix[y][x])
} else {
direction = 0
leftBound++
}
}
}
return path
}
// @lc code=end