1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00

go: add «2326. Spiral Matrix IV»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-09-09 17:29:48 +02:00
parent 87c2fb3895
commit cbed4bec90
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

39
go/spiral-matrix-iv.go Normal file
View 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
}