Shohei Yoshida
Shohei Yoshida's Blog

Follow

Shohei Yoshida's Blog

Follow

LeetCode 841. Keys and Rooms in F#

Shohei Yoshida's photo
Shohei Yoshida
·Dec 20, 2022·

1 min read

URL

Keys and Rooms - LeetCode

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/problems/0841/main.fsx

let canVisitAllRooms (rooms: int list[]) : bool =
    let rec canVisitAllRooms' room (rooms: int list[]) visited =
        if rooms.Length = (Seq.length visited) then
            true, visited
        else
            rooms.[room]
            |> List.fold
                (fun (ok, visited) nextRoom ->
                    if ok then
                        ok, visited
                    elif Set.contains nextRoom visited then
                        false, visited
                    else
                        canVisitAllRooms' nextRoom rooms (Set.add nextRoom visited))
                (false, visited)

    canVisitAllRooms' 0 rooms (Set.add 0 Set.empty) |> fst
 
Share this