function Main(line) {
  let [first, second, third, ...data] = line.trim().split("\n");

  const [R, C] = first
    .trim()
    .split(" ")
    .map((f) => Number(f - 1));
  const [stR, stC] = second
    .trim()
    .split(" ")
    .map((f) => Number(f - 1));
  const [edR, edC] = third
    .trim()
    .split(" ")
    .map((f) => Number(f - 1));

  const map = [];
  const dp = [];
  data.forEach((v, i) => {
    map[i] = v.trim().split("");
    dp[i] = v
      .trim()
      .split("")
      .map((v) => Number.MAX_SAFE_INTEGER);
  });

  dp[stR][stC] = 0;

  let current_Queue = [{ x: stR, y: stC }];
  let next_Queue = [];

  const xAxis = [0, 1, 0, -1];
  const yAxis = [1, 0, -1, 0];
  const range_3 = [0, 1, 2, 3];

  while (current_Queue.length > 0 || next_Queue.length > 0) {
    if (current_Queue.length === 0) {
      current_Queue = [...next_Queue];
      next_Queue = [];
    }
    const { x, y } = current_Queue.shift();

    for (const val of range_3) {
      const xX = x + xAxis[val];
      const yY = y + yAxis[val];
      if (isOut(xX, yY)) continue;

      if (dp[x][y] + 0 < dp[xX][yY]) {
        dp[xX][yY] = dp[x][y];
        current_Queue.push({ x: xX, y: yY });
      }
    }
    for (let i = -2; i <= 2; i++) {
      for (let j = -2; j <= 2; j++) {
        if (
          (i === 0 && j === 0) ||
          (i === 1 && j === 0) ||
          (i === 0 && j === 1) ||
          (i === -1 && j === 0) ||
          (i === 0 && j === -1)
        ) {
          continue;
        }
        const xX = x + i;
        const yY = y + j;
        if (isOut(xX, yY)) continue;
        if (dp[x][y] + 1 < dp[xX][yY]) {
          dp[xX][yY] = dp[x][y] + 1;
          next_Queue.push({ x: xX, y: yY });
        }
      }
    }

  }
  if(dp[edR][edC] === Number.MAX_SAFE_INTEGER ){
    console.log(-1);
  } else {
    console.log(dp[edR][edC]);
  }

  function isOut(x, y) {
    if (x < 0 || x > R || y < 0 || y > C) {
      return true;
    }
    if (map[x][y] === "#") {
      return true;
    }
    return false;
  }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
