import sys from collections import deque def main(): H, W, ra, ca, rb, cb = map(int, sys.stdin.readline().split()) grid = [] for _ in range(H): grid.append(sys.stdin.readline().strip()) # Convert to 0-based indices ra -= 1 ca -= 1 rb -= 1 cb -= 1 # Directions: up, down, left, right dirs = [(-1,0), (1,0), (0,-1), (0,1)] # BFS queue: (ushi_r, ushi_c, hikari_r, hikari_c, moves) q = deque() visited = dict() start_state = (ra, ca, rb, cb) q.append((ra, ca, rb, cb, 0)) visited[start_state] = 0 answer = -1 while q: ur, uc, hr, hc, moves = q.popleft() # Check if both are at their target positions if ur == rb and uc == cb and hr == ra and hc == ca: answer = moves break # Generate possible moves # Either Ushi moves or Hikari moves # First, try moving Ushi for dr, dc in dirs: nur = ur + dr nuc = uc + dc # Check boundaries and obstacle if 0 <= nur < H and 0 <= nuc < W and grid[nur][nuc] == '.': # Check if the new position is not occupied by Hikari if (nur, nuc) != (hr, hc): new_state = (nur, nuc, hr, hc) if new_state not in visited or visited[new_state] > moves + 1: visited[new_state] = moves + 1 q.append((nur, nuc, hr, hc, moves + 1)) # Then, try moving Hikari for dr, dc in dirs: nhr = hr + dr nhc = hc + dc # Check boundaries and obstacle if 0 <= nhr < H and 0 <= nhc < W and grid[nhr][nhc] == '.': # Check if the new position is not occupied by Ushi if (nhr, nhc) != (ur, uc): new_state = (ur, uc, nhr, nhc) if new_state not in visited or visited[new_state] > moves + 1: visited[new_state] = moves + 1 q.append((ur, uc, nhr, nhc, moves + 1)) print(answer) if __name__ == '__main__': main()