H,W,*a = $<.take(3).join.split.map &:to_i
a.map!{_1-1}
A = [p] * ((H+1)<<10)
B = (1<<10) - 1
C = A.dup
D = a[3]
M = (1..H).map { s=gets; s[W]='##'; s }
M.fill -(?#*(W+2)), H, 2
h = [*-2..2].repeated_permutation(2).group_by{_1.abs+_2.abs}
N = h[1]
P = h[2]+h[3]+h[4]
Q = [(a[0]<<10)+a[1]]
R = []
S = M[a[2]]
p (0..).each {|n|
  R.pop(H*W).each {
    h,w = _1>>10, _1&B
    P.each {|r,c| M[r+=h][c+=w] == ?. and Q << (r<<10)+c }
  }
  while Q[0]
    Q.pop(H*W).each {|q|
      M[h=q>>10][w=q&B] = ?*
      N.each {|r,c|
        m = M[r+=h][c+=w]
        a = (r<<10) + c
        if m == ?. && !A[a]
          A[a] = n
          Q << a
        elsif m == ?# && !C[q]
          C[q] = n
          R << q
        end
      }
    }
  end
  break n if S[D] != ?.
  break -1 if !R[0]
}