from collections import deque # 输入数据 n, m = map(int, input().split()) xs, ys, xt, yt = map(int, input().split()) # 读入地图(转为字符列表) grid = [list(input().strip()) for _ in range(n)] # 边界特判:起点终点相同或起点/终点是墙 if xs == xt and ys == yt: print(0) exit() if grid[xs-1][ys-1] == '*' or grid[xt-1][yt-1] == '*': print(-1) exit() # 初始化访问数组(比 set 更快 + 内存更少) visited = [[False] * m for _ in range(n)] directions = [(0, -1), (0, 1), (1, 0), (-1, 0)] # 上下左右 # BFS 初始化队列(起始点坐标、距离) queue = deque([(xs-1, ys-1, 0)]) visited[xs-1][ys-1] = True while queue: x, y, d = queue.popleft() # 到达终点,返回答案 if x == xt - 1 and y == yt - 1: print(d) exit() # 遍历四个方向 for dx, dy in directions: nx, ny = x + dx, y + dy # ❗ 关键优化:一旦不满足条件立即 continue(利用短路) if nx < 0 or nx >= n or ny < 0 or ny >= m or visited[nx][ny] or grid[nx][ny] == '*': continue # 合法位置:标记已访问并加入队列 visited[nx][ny] = True queue.append((nx, ny, d + 1)) # 如果走到最后还没找到路径(理论上不可能,但保险起见) print(-1)