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
}