const { listenerCount } = require("process");

function main(input = "") {
    const WALL = 99999999;
    let callback = (v) => (v === "#" ? WALL : v === "." ? 0 : Number(v))
    const lines = input.split("\n");
    const header = lines.slice(0, 3).map((line) => (line.split(" ").map((v) => (Number(v)))));
    const H = header[0][0], W = header[0][1];
    const Ch = header[1][0] - 1, Cw = header[1][1] - 1;
    const Dh = header[2][0] - 1, Dw = header[2][1] - 1;
    const Dest = Dh * W + Dw;
    const GRID = lines.slice(3).map((line) => (line.split("").map((v) => (v === "#" ? WALL : 0))))
    const MAZE = new Int32Array(Array().concat(...GRID));

    let fill = (h = 0, w = 0, v = 0, arr = []) => {
        let id = h * W + w;
        if (MAZE[id] < v) {
            MAZE[id] = v;
            arr.push(id)
            if (0 <= h - 1) fill(h - 1, w, v, arr);
            if (h + 1 < H) fill(h + 1, w, v, arr);
            if (0 <= w - 1) fill(h, w - 1, v, arr);
            if (w + 1 < W) fill(h, w + 1, v, arr);
        }
    }

    let getWarpList = (h = 0, w = 0, area = [0]) => {
        let arr = [];
        area.forEach((v) => {
            let ih = 0 | v / W;
            let iw = v - ih * W;
            _warpList(iw, iw, arr);
        })
        return arr;
    }

    let _warpList = (h = 0, w = 0, arr = []) => {
        let v = MAZE[h * W + w];
        for (let ih = -2; ih <= 2; ih++) {
            let th = h + ih;
            if (0 <= th && th < H) {
                for (let iw = -2; iw <= 2; iw++) {
                    let tw = w + iw;
                    if (0 <= tw && tw < W) {
                        if (MAZE[th * W + tw] < v) {
                            arr.push([th, tw]);
                        }
                    }
                }
            }
        }
    }

    let area = [];
    let ch = Ch, cw = Cw;
    let color = 1;
    fill(ch, cw, color, area);
    while (true) {
        color++;
        let lst = getWarpList(ch, cw, area)
        area.length = 0;
        for (let i = 0; i < lst.length; i++) {
            let xy = lst[i];
            fill(xy[0], xy[1], color, area);
        }
        if (MAZE[Dest] !== 0 || area.length === 0) {
            break;
        }
    }

    return MAZE[Dest] - 1;
}


//******************************
exports.main = main;

function Main(input) {
    console.log(main(input.trim()));
}

if (process.argv[2] !== "test") {
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}