LeetCode 2326. Spiral Matrix IV in F#
URL
https://leetcode.com/problems/spiral-matrix-iv/description/?envType=daily-question&envId=2024-09-09
Code
type MyList =
| Nil
| Node of int * MyList
let spiralMatrix (m: int) (n: int) (head: MyList) : int[,] =
let steps = [| (0, 1); (1, 0); (0, -1); (-1, 0) |]
let rec spiralMatrix' node dir row col (acc: int[,]) =
match node with
| Nil -> acc
| Node(v, next) ->
acc.[row, col] <- v
let r, c = row + fst steps.[dir], col + snd steps.[dir]
if r >= 0 && r < m && c >= 0 && c < n && acc.[r, c] = -1 then
spiralMatrix' next dir r c acc
else
let d = (dir + 1) % 4
let r, c = row + fst steps.[d], col + snd steps.[d]
spiralMatrix' next d r c acc
let acc = Array2D.init m n (fun _ _ -> -1)
spiralMatrix' head 0 0 0 acc