open System.Linq

let sizeH, sizeW =
    stdin.ReadLine().Split().Select(int).ToArray()
    |> fun a -> a.[0], a.[1]

let startH, startW =
    stdin.ReadLine().Split().Select(int).ToArray()
    |> fun a -> a.[0] - 1, a.[1] - 1

let goalH, goalW =
    stdin.ReadLine().Split().Select(int).ToArray()
    |> fun a -> a.[0] - 1, a.[1] - 1

// int: 必要ワープ数, -1:未判定 , -2: 壁
let grid =

    let tmpgrid =
        [| for _ in 1 .. sizeH -> stdin.ReadLine().ToCharArray() |]
        |> Array.map (fun sq ->
            sq
            |> Array.map (fun c -> if c = '#' then -2 else -1))

    tmpgrid.[startH].[startW] <- 0
    tmpgrid

let findAllSquares num =

    // printfn "Find All %d" num

    let mutable squares = []

    for i1 in 0 .. sizeH - 1 do
        for i2 in 0 .. sizeW - 1 do
            if grid.[i1].[i2] = num then squares <- (i1, i2) :: squares

    // printfn "Squares Found: %A" squares

    squares.ToArray()

let checkGoal () = grid.[goalH].[goalW] <> -1

let isBlankRoad (h, w) =
    (0 <= h)
    && (h <= sizeH - 1)
    && (0 <= w)
    && (w <= sizeW - 1)
    && (grid.[h].[w] = -1)

let walkableNeibors = 0

let walkables (h, w) =

    [| (-1, 0); (0, 1); (1, 0); (0, -1) |]
    |> Array.map (fun (addH, addW) -> h + addH, w + addW)
    |> Array.filter (isBlankRoad)

let warpableBase =
    [| for ih in -2 .. 2 do
        for iw in -2 .. 2 -> (ih, iw) |]
    |> Array.except [| (-1, 0)
                       (0, 1)
                       (0, 0)
                       (1, 0)
                       (0, -1) |]

let warpables (h, w) =
    warpableBase
    |> Array.map (fun (addH, addW) -> h + addH, w + addW)
    |> Array.filter (isBlankRoad)

let rec walkAround from =

    let rec walkAroundR lastDetermined =
        // printfn "WalkAround %d\n- (last determined:%A)" from lastDetermined

        if Array.isEmpty lastDetermined then
            ()
        else
            let newlyDetermined =
                lastDetermined
                |> Array.collect (walkables)
                |> Array.distinct

            // printfn "Newly Determined: %A" newlyDetermined

            newlyDetermined
            |> Array.iter (fun (h, w) -> grid.[h].[w] <- from)

            if checkGoal () then () else walkAroundR newlyDetermined

    walkAroundR (findAllSquares from) |> ignore

    if checkGoal () then () else warp from

and warp from =

    // printfn "Warp %d to %d" from (from + 1)

    let next = from + 1

    let warped =
        findAllSquares from
        |> Array.collect (warpables)
        |> Array.distinct

    // printfn "Newly Warped: %A" warped

    if Array.isEmpty warped then
        ()
    else
        warped
        |> Array.iter (fun (h, w) -> grid.[h].[w] <- next)

        if checkGoal () then () else walkAround next

walkAround 0
printfn "%d" grid.[goalH].[goalW]
