-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathspiral_matrix_II.go
76 lines (73 loc) · 1.07 KB
/
spiral_matrix_II.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
69
70
71
72
73
74
75
76
package spiral_matrix_II
const (
up string = "up"
down = "down"
left = "left"
right = "right"
)
func generateMatrix(n int) [][]int {
matrix := make([][]int, n)
for i := range matrix {
matrix[i] = make([]int, n)
}
if n == 0 {
return matrix
}
rows, cols := n, n
status := right
i, j := 0, -1
current := 1
for rows != 0 && cols != 0 {
switch status {
case right:
cnt := cols
for {
if cnt == 0 {
break
}
j, cnt = j+1, cnt-1
matrix[i][j] = current
current++
}
rows--
status = down
case down:
cnt := rows
for {
if cnt == 0 {
break
}
i, cnt = i+1, cnt-1
matrix[i][j] = current
current++
}
cols--
status = left
case left:
cnt := cols
for {
if cnt == 0 {
break
}
j, cnt = j-1, cnt-1
matrix[i][j] = current
current++
}
rows--
status = up
case up:
cnt := rows
for {
if cnt == 0 {
break
}
i, cnt = i-1, cnt-1
matrix[i][j] = current
current++
}
cols--
status = right
}
}
return matrix
}