Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 766. Toeplitz Matrix in F#

Shohei Yoshida's photo
Shohei Yoshida
·Oct 31, 2022·

1 min read

URL

leetcode.com/problems/toeplitz-matrix

Code

hashnode.com/draft/635f2a27b7bb8c3f4ee4325c

let isToeplitzMatrix (matrix: int [,]) : bool =
    let rec check row col v rows cols (matrix: int [,]) =
        if row >= rows || col >= cols then
            true
        else if v <> matrix.[row, col] then
            false
        else
            check (row + 1) (col + 1) v rows cols matrix

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

    let rowOK =
        seq { 0 .. (rows - 1) }
        |> Seq.forall (fun row -> check (row + 1) 1 matrix.[row, 0] rows cols matrix)

    let colOK =
        seq { 0 .. (cols - 1) }
        |> Seq.forall (fun col -> check 1 (col + 1) matrix.[0, col] rows cols matrix)

    rowOK && colOK
 
Share this