Scanf.sscanf (read_line ()) "%d %d" (fun h w ->
    let a = Array.init h (fun _ -> Bytes.of_string @@ read_line ()) in
    let rec loop_y y acc =
        let rec loop_x x acc =
            if x < 0 then acc else loop_x (x - 1) (if Bytes.get a.(y) x = '#' then (x, y) :: acc else acc)
        in
        if y < 0 then acc else loop_y (y - 1) (loop_x (w - 1) acc)
    in

    let rec bfs step next = function
        | [] -> if next = [] then step - 1 else bfs (step + 1) [] next
        | (x, y) :: tl ->
                let next = if x > 0     && Bytes.get a.(y) (x - 1) = '.' then (Bytes.set a.(y) (x - 1) '#'; (x - 1, y) :: next) else next in
                let next = if y > 0     && Bytes.get a.(y - 1) (x) = '.' then (Bytes.set a.(y - 1) (x) '#'; (x, y - 1) :: next) else next in
                let next = if x < w - 1 && Bytes.get a.(y) (x + 1) = '.' then (Bytes.set a.(y) (x + 1) '#'; (x + 1, y) :: next) else next in
                let next = if y < h - 1 && Bytes.get a.(y + 1) (x) = '.' then (Bytes.set a.(y + 1) (x) '#'; (x, y + 1) :: next) else next in
                bfs step next tl
    in
    bfs 1 [] (loop_y (h - 1) []) |> Printf.printf "%d\n"
)
