""" https://yukicoder.me/problems/no/1572 サイコロの向きは、6通りしかない 頑張って推移を書けばおk 0 表 1 上 2 右 3 下 4 左 5 裏 """ import sys from sys import stdin from collections import deque def encode(x,y,state): return H*W*state + y*H + x def decode(now): state = now // (H*W) y = (now % (H*W)) // H x = (now % (H*W)) % H return x,y,state def chdi(state,movedir): if state == 0: if movedir == "U": return 1 elif movedir == "R": return 2 elif movedir == "D": return 3 else: return 4 elif state == 1: #上 if movedir == "U": return 5 elif movedir == "D": return 0 else: return 1 elif state == 2: #右 if movedir == "R": return 5 elif movedir == "L": return 0 else: return 2 elif state == 3: #下 if movedir == "D": return 5 elif movedir == "U": return 0 else: return 3 elif state == 4: #左 if movedir == "L": return 5 elif movedir == "R": return 0 else: return 4 else: #裏 if movedir == "U": return 3 elif movedir == "R": return 4 elif movedir == "D": return 1 else: return 2 H,W = map(int,stdin.readline().split()) sx,sy = map(int,stdin.readline().split()) gx,gy = map(int,stdin.readline().split()) sx -= 1 sy -= 1 gx -= 1 gy -= 1 A = [ list(stdin.readline()[:-1]) for i in range(H) ] d = [float("inf")] * (H*W*6) q = deque([encode(sx,sy,0)]) d[encode(sx,sy,0)] = 0 while q: code = q.popleft() x,y,state = decode(code) if x != 0 and A[x-1][y] != "#": nx,ny,nstate = x-1,y,chdi(state,"U") ncode = encode(nx,ny,nstate) if d[ncode] > d[code] + 1: d[ncode] = d[code] + 1 q.append(ncode) if x != H-1 and A[x+1][y] != "#": nx,ny,nstate = x+1,y,chdi(state,"D") ncode = encode(nx,ny,nstate) if d[ncode] > d[code] + 1: d[ncode] = d[code] + 1 q.append(ncode) if y != 0 and A[x][y-1] != "#": nx,ny,nstate = x,y-1,chdi(state,"L") ncode = encode(nx,ny,nstate) if d[ncode] > d[code] + 1: d[ncode] = d[code] + 1 q.append(ncode) if y != W-1 and A[x][y+1] != "#": nx,ny,nstate = x,y+1,chdi(state,"R") ncode = encode(nx,ny,nstate) if d[ncode] > d[code] + 1: d[ncode] = d[code] + 1 q.append(ncode) ans = d[encode(gx,gy,0)] print (ans if ans != float("inf") else -1)