LeetCode 1329. Sort the Matrix Diagonally in F#

URL

leetcode.com/problems/sort-the-matrix-diago..

Code

github.com/syohex/dotnet-study/tree/master/..

let diagonalSort (mat: int [,]) : int [,] =
    let mutable m: Map<int, int list> = Map.empty

    let rows = Array2D.length1 mat
    let cols = Array2D.length2 mat

    for i in 0 .. (rows - 1) do
        for j in 0 .. (cols - 1) do
            let key = i - j

            match Map.tryFind key m with
            | None -> m <- Map.add key [ mat[i, j] ] m
            | Some (v) ->
                let v' = (mat[i, j] :: v) |> List.sort
                m <- Map.add key v' m

    for i in 0 .. (rows - 1) do
        for j in 0 .. (cols - 1) do
            let key = i - j

            match Map.find key m with
            | [] -> failwith "never reach here"
            | h :: t ->
                mat.[i, j] <- h
                m <- Map.add key t m

    mat