import java.util.*

fun main(args : Array<String>) {
    val (h, w) = readLine()!!.split(" ").map { it.toInt() }
    val c = readLine()!!.split(" ").map { it.toInt()-1 }
    val d = readLine()!!.split(" ").map { it.toInt()-1 }
    val ss = Array(h) { readLine()!! }

    val seen = Array(h) { IntArray(w) {-1} }
    val bfs = PriorityQueue<Step>(){ s1, s2 ->
        return@PriorityQueue s1.warp - s2.warp
    }

    bfs.add(Step(c[0], c[1], 0))
    seen[c[0]][c[1]] = 0

    while (bfs.isNotEmpty()) {
        val step = bfs.poll()
        if (seen[step.h][step.w] < step.warp) continue

        if (step.h == d[0] && step.w == d[1]) {
            println(step.warp)
            return
        }

        val hs = Math.max(step.h-2, 0)
        val he = Math.min(step.h+2, h-1)
        val ws = Math.max(step.w-2, 0)
        val we = Math.min(step.w+2, w-1)

        for (i in hs..he) {
            for (j in ws..we) {
                if (ss[i][j] == '.') {
                    if ((i == step.h-1 && j == step.w) || (i == step.h+1 && j == step.w) ||
                        (i == step.h && j == step.w-1) || (i == step.h && j == step.w+1)) {
                        if (seen[i][j] == -1 || seen[i][j] > step.warp) {
                            bfs.add(Step(i, j, step.warp))
                            seen[i][j] = step.warp
                        }
                    } else if (seen[i][j] == -1 || seen[i][j] > step.warp+1) {
                        bfs.add(Step(i, j, step.warp+1))
                        seen[i][j] = step.warp+1
                    }
                }
            }
        }
    }

    println(-1)
}

data class Step(val h: Int, val w: Int, val warp: Int)