// The main code is at the very bottom.

#[allow(unused_imports)]
use {
  lib::byte::ByteChar,
  std::cell::{Cell, RefCell},
  std::cmp::{
    self,
    Ordering::{self, *},
    Reverse,
  },
  std::collections::*,
  std::convert::identity,
  std::fmt::{self, Debug, Display, Formatter},
  std::io::prelude::*,
  std::iter::{self, FromIterator},
  std::marker::PhantomData,
  std::mem,
  std::num::Wrapping,
  std::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive},
  std::process,
  std::rc::Rc,
  std::thread,
  std::time::{Duration, Instant},
  std::{char, f32, f64, i128, i16, i32, i64, i8, isize, str, u128, u16, u32, u64, u8, usize},
};

#[allow(unused_imports)]
#[macro_use]
pub mod lib {
  pub mod byte {
    pub use self::byte_char::*;

    mod byte_char {
      use std::error::Error;
      use std::fmt::{self, Debug, Display, Formatter};
      use std::str::FromStr;

      #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
      #[repr(transparent)]
      pub struct ByteChar(pub u8);

      impl Debug for ByteChar {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          write!(f, "b'{}'", self.0 as char)
        }
      }

      impl Display for ByteChar {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          write!(f, "{}", self.0 as char)
        }
      }

      impl FromStr for ByteChar {
        type Err = ParseByteCharError;

        fn from_str(s: &str) -> Result<ByteChar, ParseByteCharError> {
          match s.as_bytes().len() {
            1 => Ok(ByteChar(s.as_bytes()[0])),
            0 => Err(ParseByteCharErrorKind::EmptyStr.into()),
            _ => Err(ParseByteCharErrorKind::TooManyBytes.into()),
          }
        }
      }

      #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
      pub struct ParseByteCharError {
        kind: ParseByteCharErrorKind,
      }

      impl Display for ParseByteCharError {
        fn fmt(&self, f: &mut Formatter) -> fmt::Result {
          f.write_str(match self.kind {
            ParseByteCharErrorKind::EmptyStr => "empty string",
            ParseByteCharErrorKind::TooManyBytes => "too many bytes",
          })
        }
      }

      impl Error for ParseByteCharError {}

      #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
      enum ParseByteCharErrorKind {
        EmptyStr,
        TooManyBytes,
      }

      impl From<ParseByteCharErrorKind> for ParseByteCharError {
        fn from(kind: ParseByteCharErrorKind) -> ParseByteCharError {
          ParseByteCharError { kind }
        }
      }
    }
  }

  pub mod io {
    pub use self::scanner::*;

    mod scanner {
      use std::io::{self, BufRead};
      use std::iter;
      use std::str::FromStr;

      #[derive(Debug)]
      pub struct Scanner<R> {
        reader: R,
        buf: String,
        pos: usize,
      }

      impl<R: BufRead> Scanner<R> {
        pub fn new(reader: R) -> Self {
          Scanner {
            reader,
            buf: String::new(),
            pos: 0,
          }
        }

        pub fn next(&mut self) -> io::Result<&str> {
          let start = loop {
            match self.rest().find(|c| c != ' ') {
              Some(i) => break i,
              None => self.fill_buf()?,
            }
          };
          self.pos += start;
          let len = self.rest().find(' ').unwrap_or(self.rest().len());
          let s = &self.buf[self.pos..][..len]; // self.rest()[..len]
          self.pos += len;
          Ok(s)
        }

        pub fn parse_next<T>(&mut self) -> io::Result<Result<T, T::Err>>
        where
          T: FromStr,
        {
          Ok(self.next()?.parse())
        }

        pub fn parse_next_n<T>(&mut self, n: usize) -> io::Result<Result<Vec<T>, T::Err>>
        where
          T: FromStr,
        {
          iter::repeat_with(|| self.parse_next()).take(n).collect()
        }

        pub fn map_next_bytes<T, F>(&mut self, mut f: F) -> io::Result<Vec<T>>
        where
          F: FnMut(u8) -> T,
        {
          Ok(self.next()?.bytes().map(&mut f).collect())
        }

        pub fn map_next_bytes_n<T, F>(&mut self, n: usize, mut f: F) -> io::Result<Vec<Vec<T>>>
        where
          F: FnMut(u8) -> T,
        {
          iter::repeat_with(|| self.map_next_bytes(&mut f))
            .take(n)
            .collect()
        }

        fn rest(&self) -> &str {
          &self.buf[self.pos..]
        }

        fn fill_buf(&mut self) -> io::Result<()> {
          self.buf.clear();
          self.pos = 0;
          let read = self.reader.read_line(&mut self.buf)?;
          if read == 0 {
            return Err(io::ErrorKind::UnexpectedEof.into());
          }
          if *self.buf.as_bytes().last().unwrap() == b'\n' {
            self.buf.pop();
          }
          Ok(())
        }
      }
    }
  }
}

#[allow(unused_imports)]
pub mod quick_find {
  use std::mem;

  #[derive(Clone, Debug)]
  pub struct QuickFind {
    elems: Vec<Vec<usize>>,
    reprs: Vec<usize>,
    sets_len: usize,
  }

  impl QuickFind {
    pub fn new(len: usize) -> Self {
      Self {
        elems: (0..len).map(|i| vec![i]).collect(),
        reprs: (0..len).collect(),
        sets_len: len,
      }
    }

    pub fn len(&self) -> usize {
      self.reprs.len()
    }

    pub fn sets_len(&self) -> usize {
      self.sets_len
    }

    pub fn repr(&self, i: usize) -> usize {
      self.reprs[i]
    }

    pub fn unite_sets(&mut self, i: usize, j: usize) -> bool {
      let mut i = self.repr(i);
      let mut j = self.repr(j);

      if i == j {
        return false;
      }
      if self.elems[i].len() < self.elems[j].len() {
        mem::swap(&mut i, &mut j);
      }

      debug_assert!(self.elems[i].len() >= self.elems[j].len());

      for &k in &self.elems[j] {
        self.reprs[k] = i;
      }
      let mut elems_j = mem::replace(&mut self.elems[j], vec![]);
      self.elems[i].append(&mut elems_j);
      self.sets_len -= 1;
      true
    }

    pub fn belong_to_same_set(&self, i: usize, j: usize) -> bool {
      self.repr(i) == self.repr(j)
    }

    pub fn set(&self, i: usize) -> &[usize] {
      &self.elems[self.repr(i)]
    }
  }
}

#[allow(unused_macros)]
macro_rules! eprint {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::eprint!($($arg)*)
    }
  };
}
#[allow(unused_macros)]
macro_rules! eprintln {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::eprintln!($($arg)*)
    }
  };
}
#[allow(unused_macros)]
macro_rules! dbg {
  ($($arg:tt)*) => {
    if cfg!(debug_assertions) {
      std::dbg!($($arg)*)
    } else {
      ($($arg)*)
    }
  };
}

const CUSTOM_STACK_SIZE_MIB: Option<usize> = Some(1024);
const INTERACTIVE: bool = false;

fn main() -> std::io::Result<()> {
  match CUSTOM_STACK_SIZE_MIB {
    Some(stack_size_mib) => std::thread::Builder::new()
      .name("run_solver".to_owned())
      .stack_size(stack_size_mib * 1024 * 1024)
      .spawn(run_solver)?
      .join()
      .unwrap(),
    None => run_solver(),
  }
}

fn run_solver() -> std::io::Result<()> {
  let stdin = std::io::stdin();
  let reader = stdin.lock();
  let stdout = std::io::stdout();
  let writer = stdout.lock();
  macro_rules! with_wrapper {
    ($($wrapper:expr)?) => {{
      let mut writer = $($wrapper)?(writer);
      solve(reader, &mut writer)?;
      writer.flush()
    }};
  }
  if cfg!(debug_assertions) || INTERACTIVE {
    with_wrapper!()
  } else {
    with_wrapper!(std::io::BufWriter::new)
  }
}

fn solve<R, W>(reader: R, mut writer: W) -> std::io::Result<()>
where
  R: BufRead,
  W: Write,
{
  let mut _scanner = lib::io::Scanner::new(reader);
  #[allow(unused_macros)]
  macro_rules! scan {
    ($T:ty) => {
      _scanner.parse_next::<$T>()?.unwrap()
    };
    ($($T:ty),+) => {
      ($(scan!($T)),+)
    };
    ($T:ty; $n:expr) => {
      _scanner.parse_next_n::<$T>($n)?.unwrap()
    };
    ($($T:ty),+; $n:expr) => {
      iter::repeat_with(|| -> std::io::Result<_> { Ok(($(scan!($T)),+)) })
        .take($n)
        .collect::<std::io::Result<Vec<_>>>()?
    };
  }
  #[allow(unused_macros)]
  macro_rules! scan_bytes_map {
    ($f:expr) => {
      _scanner.map_next_bytes($f)?
    };
    ($f:expr; $n:expr) => {
      _scanner.map_next_bytes_n($n, $f)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! print {
    ($($arg:tt)*) => {
      write!(writer, $($arg)*)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! println {
    ($($arg:tt)*) => {
      writeln!(writer, $($arg)*)?
    };
  }
  #[allow(unused_macros)]
  macro_rules! answer {
    ($($arg:tt)*) => {{
      println!($($arg)*);
      return Ok(());
    }};
  }
  {
    let (h, w) = scan!(usize, usize);
    let (c_h, c_w) = scan!(usize, usize);
    let (d_h, d_w) = scan!(usize, usize);
    let s = scan_bytes_map!(ByteChar; h);

    let (c_h, c_w) = (c_h - 1, c_w - 1);
    let (d_h, d_w) = (d_h - 1, d_w - 1);

    use quick_find::QuickFind;

    let idx = move |i: usize, j: usize| w * i + j;
    let pos = move |idx: usize| (idx / w, idx % w);

    let mut uf = QuickFind::new(h * w);
    for i in 0..h {
      for j in 0..w {
        if s[i][j].0 == b'#' {
          continue;
        }
        for k in 0..4 {
          let dy = [!0, 1, 0, 0];
          let dx = [0, 0, !0, 1];
          let i2 = i.wrapping_add(dy[k]);
          let j2 = j.wrapping_add(dx[k]);
          if i2 < h && j2 < w && s[i2][j2].0 == b'.' {
            uf.unite_sets(idx(i, j), idx(i2, j2));
          }
        }
      }
    }

    // debug
    {
      let mut set = HashSet::new();
      for id in 0..h * w {
        if set.insert(uf.repr(id)) {
          let (y, x) = pos(id);
          eprintln!("({}, {}) (repr = {}): {:?}", y, x, uf.repr(id), uf.set(id));
        }
      }
    }

    let mut g = vec![HashSet::new(); h * w];
    let mut visited = vec![false; h * w];
    for i in 0..h {
      for j in 0..w {
        if s[i][j].0 == b'#' {
          continue;
        }
        let repr = uf.repr(idx(i, j));
        if visited[repr] {
          continue;
        }
        visited[repr] = true;
        for &id_inner in uf.set(idx(i, j)) {
          let (i, j) = pos(id_inner);
          eprintln!("({}, {}) ->", i, j);
          for &dy in &[!0 - 1, !0, 0, 1, 2] {
            for &dx in &[!0 - 1, !0, 0, 1, 2] {
              let i2 = i.wrapping_add(dy);
              let j2 = j.wrapping_add(dx);
              if i2 >= h || j2 >= w || s[i2][j2].0 == b'#' {
                continue;
              }
              eprintln!("  ({}, {})", i2, j2);
              let repr2 = uf.repr(idx(i2, j2));
              g[repr].insert(repr2);
              g[repr2].insert(repr);
            }
          }
        }
      }
    }
    eprintln!("{:?}", g);

    let mut ans = None;
    let mut queue = VecDeque::new();
    let mut visited = vec![false; h * w];
    let d_repr = uf.repr(idx(d_h, d_w));
    {
      let c_repr = uf.repr(idx(c_h, c_w));
      if c_repr == d_repr {
        answer!("{}", 0);
      }
      queue.push_back((c_repr, 0u64));
      visited[c_repr] = true;
    }
    'outer: while let Some((repr, dist)) = queue.pop_front() {
      for &repr2 in &g[repr] {
        if repr2 == d_repr {
          ans = Some(dist + 1);
          break 'outer;
        }
        if visited[repr2] {
          continue;
        }
        visited[repr2] = true;
        queue.push_back((repr2, dist + 1));
      }
    }
    if let Some(ans) = ans {
      println!("{}", ans);
    } else {
      println!("-1");
    }
  }
  #[allow(unreachable_code)]
  Ok(())
}


Measured memory_bytes: 131488