go: add «2326. Spiral Matrix IV»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
87c2fb3895
commit
cbed4bec90
1 changed files with 39 additions and 0 deletions
39
go/spiral-matrix-iv.go
Normal file
39
go/spiral-matrix-iv.go
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
const (
|
||||||
|
UNSET int = -1
|
||||||
|
)
|
||||||
|
|
||||||
|
func spiralMatrix(m int, n int, node *ListNode) [][]int {
|
||||||
|
matrix := make([][]int, m)
|
||||||
|
for y := 0; y < m; y++ {
|
||||||
|
matrix[y] = make([]int, n)
|
||||||
|
for x := 0; x < n; x++ {
|
||||||
|
matrix[y][x] = UNSET
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Next := func(dy, dx, y, x int) (int, int, int, int) {
|
||||||
|
// Rotate if we cannot move to the next position
|
||||||
|
if (y+dy < 0 || y+dy >= m) || (x+dx < 0 || x+dx >= n) || matrix[y+dy][x+dx] != UNSET {
|
||||||
|
// (0, 1) -> (1, 0) -> (0, -1) -> (-1, 0) -> (0, 1)
|
||||||
|
dy, dx = dx, -dy
|
||||||
|
}
|
||||||
|
|
||||||
|
y += dy
|
||||||
|
x += dx
|
||||||
|
|
||||||
|
return dy, dx, y, x
|
||||||
|
}
|
||||||
|
|
||||||
|
y, x := 0, 0
|
||||||
|
dy, dx := 0, 1
|
||||||
|
for node != nil {
|
||||||
|
matrix[y][x] = node.Val
|
||||||
|
|
||||||
|
dy, dx, y, x = Next(dy, dx, y, x)
|
||||||
|
node = node.Next
|
||||||
|
}
|
||||||
|
|
||||||
|
return matrix
|
||||||
|
}
|
Loading…
Reference in a new issue