from collections import*

I=9**9

(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)

m,d=list(zip(*eval('(input(),[I]*w),'*h)))

q=deque([(s-1,t-1,1)])

r=list(range(-2,3))

while q:

 y,x,c=q.popleft()

 if d[y][x]>c:

  for a in r:

    for b in r:i=a+y;j=b+x;d[y][x]=c;h>i>-1<j<w!=m[i][j]>'#'!=(abs(a)+abs(b)<2!=q.appendleft((i,j,c)),q.append((i,j,c+1)))

print((d[f-1][g-1]%I-1))
from collections import*

I=9**9

(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)

m,d=list(zip(*eval('(input(),[I]*w),'*h)))

q=deque([(s-1,t-1,1)])

while q:

 y,x,c=q.popleft()

 if d[y][x]>c:

  for a in range(25):a,b=a//5-2,a%5-2;i=a+y;j=b+x;d[y][x]=c;h>i>-1<j<w!=m[i][j]>'#'!=(abs(a)+abs(b)<2!=q.appendleft((i,j,c)),q.append((i,j,c+1)))

print((d[f-1][g-1]%I-1))
from collections import *

I = 9**9
(h, w), (s, t), (f, g) = eval("map(int,input().split())," * 3)
m, d = list(zip(*eval("(input(),[I]*w)," * h)))
q = deque([(s - 1, t - 1, 1)])
r = list(range(-2, 3))
while q:
    y, x, c = q.popleft()
    if d[y][x] > c:
        for a in r:
            for b in r:
                i = a + y
                j = b + x
                d[y][x] = c
                h > i > -1 < j < w != m[i][j] > "#" != (
                    abs(a) + abs(b) < 2 != q.appendleft((i, j, c)),
                    q.append((i, j, c + 1)),
                )
print((d[f - 1][g - 1] % I - 1))

from collections import *

I = 9**9
(h, w), (s, t), (f, g) = eval("map(int,input().split())," * 3)
m, d = list(zip(*eval("(input(),[I]*w)," * h)))
q = deque([(s - 1, t - 1, 1)])
while q:
    y, x, c = q.popleft()
    if d[y][x] > c:
        for a in range(25):
            a, b = a // 5 - 2, a % 5 - 2
            i = a + y
            j = b + x
            d[y][x] = c
            h > i > -1 < j < w != m[i][j] > "#" != (
                abs(a) + abs(b) < 2 != q.appendleft((i, j, c)),
                q.append((i, j, c + 1)),
            )
print((d[f - 1][g - 1] % I - 1))

-r = list(range(-2, 3)) -        for a in r: -            for b in r: -                i = a + y -                j = b + x -                d[y][x] = c -                h > i > -1 < j < w != m[i][j] > "#" != ( -                    abs(a) + abs(b) < 2 != q.appendleft((i, j, c)), -                    q.append((i, j, c + 1)), -                ) +        for a in range(25): +            a, b = a // 5 - 2, a % 5 - 2 +            i = a + y +            j = b + x +            d[y][x] = c +            h > i > -1 < j < w != m[i][j] > "#" != ( +                abs(a) + abs(b) < 2 != q.appendleft((i, j, c)), +                q.append((i, j, c + 1)), +            )