import java.util.ArrayDeque

fun main() {
    val inf = Int.MAX_VALUE
    val d = arrayOf(0, 1, 0, -1)

    val (h, w) = readLine()!!.split(' ').map { it.toInt() }
    val (ch, cw) = readLine()!!.split(' ').map { it.toInt() - 1 }
    val (dh, dw) = readLine()!!.split(' ').map { it.toInt() - 1 }
    val grid = (0 until h).map { readLine()!!.toCharArray() }.toTypedArray()

    val visited = Array(h) { IntArray(w) { inf } }
    val deque = ArrayDeque<Pair<Int, Int>>()
    deque.add(ch to cw)
    visited[ch][cw] = 0

    while (deque.isNotEmpty()) {
        val (ih, iw) = deque.removeFirst()

        for (i in 0 until 4) {
            val jh = ih + d[i]
            val jw = iw + d[i xor 1]

            if (jh !in 0 until h || jw !in 0 until w) continue
            if (grid[jh][jw] == '#') continue
            if (visited[jh][jw] <= visited[ih][iw]) continue

            visited[jh][jw] = visited[ih][iw]
            deque.addFirst(jh to jw)
        }

        for (i in -2..2) {
            for (j in -2..2) {
                val jh = ih + i
                val jw = iw + j
                if (jh !in 0 until h || jw !in 0 until w) continue
                if (grid[jh][jw] == '#') continue
                if (visited[jh][jw] <= visited[ih][iw]) continue

                visited[jh][jw] = visited[ih][iw] + 1
                deque.addLast(jh to jw)
            }
        }

    }

    println(if (visited[dh][dw] == inf) -1 else visited[dh][dw])
}
