Scanf.scanf "%d %d %d %d %d %d" (fun h w ch cw dh dw ->
    let ch, cw, dh, dw = ch - 1, cw - 1, dh - 1, dw - 1 in
    let s = Array.init h (fun _ -> Scanf.scanf " %s" (fun s -> s)) in
    let cost = Array.make_matrix h w max_int in
    cost.(ch).(cw) <- 0;
    let magic_cost = 1000000000 in
    let module S = Set.Make (struct type t = int * int * int let compare = compare end) in

    let rec loop rest set =
        if rest = 0 then (if cost.(dh).(dw) <> max_int then cost.(dh).(dw) / magic_cost else -1) else
            let ((cc, cy, cx) as c) = S.min_elt set in
            let set = S.remove c set in
            let rest = rest - 1 in
            let rec loop_vy vy rest set =
                let rec loop_vx vx rest set =
                    if vx = 3 || cx + vx >= w then loop_vy (vy + 1) rest set else
                        if s.(cy + vy).[cx + vx] = '#' then loop_vx (vx + 1) rest set else
                            let co = if vy = 0 && abs vx = 1 || vx = 0 && abs vy = 1 then 1 else magic_cost in
                            if cc + co < cost.(cy + vy).(cx + vx) then (
                                cost.(cy + vy).(cx + vx) <- cc + co;
                                let set = S.add (cc + co, cy + vy, cx + vx) set in
                                let rest = rest + 1 in
                                loop_vx (vx + 1) rest set
                            ) else loop_vx (vx + 1) rest set
                in
                if vy = 3 || cy + vy >= h then loop rest set else
                    loop_vx (-min 2 cx) rest set
            in
            loop_vy (-min 2 cy) rest set
    in
    loop 1 (S.singleton (0, ch, cw)) |> Printf.printf "%d\n"
)