from heapq import heappush, heappop from collections import deque def solve(): H,W = map(int,input().split()) sx,sy = map(lambda x:int(x)-1, input().split()) gx,gy = map(lambda x:int(x)-1, input().split()) A = [list(input().rstrip()) for _ in range(H)] dx = gx - sx dy = gy - sy vis = [[False]*W for _ in range(H)] dq = deque([(sx,sy)]) vis[sx][sy] = True while dq: x,y = dq.popleft() for dxx,dyy in ((1,0),(-1,0),(0,1),(0,-1)): nx,ny = x+dxx, y+dyy if 0<=nx0) and (C1+D1>0) ): assert False d2 = [[-1]*W for _ in range(H)] dq3 = deque(path) for x,y in path: d2[x][y] = 0 while dq3: x,y = dq3.popleft() for dx_,dy_ in ((1,0),(-1,0),(0,1),(0,-1)): nx,ny = x+dx_, y+dy_ if 0<=nx=0: best_v = min(best_v, d2[ii][jj]) best_h = INF for i in range(H): for j in range(W-1): if A[i][j] != '#' and A[i][j+1] != '#': for (ii,jj) in ((i,j),(i,j+1)): if d2[ii][jj]>=0: best_h = min(best_h, d2[ii][jj]) # 6) 欠けている方向だけ往復2手を入れて candidate を作る base0 = A1 + B1 + C1 + D1 # 最短路長 extra = 0 # 縦移動ゼロなら if A1+B1 == 0: if best_v < INF: extra += 2*best_v + 4 else: extra = INF # 横移動ゼロなら if C1+D1 == 0: if best_h < INF: extra += 2*best_h + 4 else: extra = INF if extra < INF: ans = base0 + extra if ans is None else min(ans, base0 + extra) print(ans if ans is not None else -1) solve() """ 2 3 2 2 2 3 .## .SG """