LeetCode/go/spiral-matrix-iv.go
Matej Focko cbed4bec90
go: add «2326. Spiral Matrix IV»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-09-09 17:29:48 +02:00

39 lines
715 B
Go

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
}