Problem:
 Score : 400 points    Problem Statement A maze is composed of a grid of H \times W squares - H vertical, W horizontal.  The square at the i -th row from the top and the j -th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is . .  There is a magician in (C_h,C_w) . He can do the following two kinds of moves:   Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.  Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.   In either case, he cannot go out of the maze.  At least how many times does he need to use the magic to reach (D_h, D_w) ?      Constraints  1 \leq H,W \leq 10^3  1 \leq C_h,D_h \leq H  1 \leq C_w,D_w \leq W  S_{ij} is # or . .  S_{C_h C_w} and S_{D_h D_w} are . .  (C_h,C_w) \neq (D_h,D_w)         Input Input is given from Standard Input in the following format:  H  W  C_h  C_w  D_h  D_w  S_{11}\ldots S_{1W}  \vdots  S_{H1}\ldots S_{HW}       Output Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w) , print -1 instead.        Sample Input 1 4 4
1 1
4 4
..#.
..#.
.#..
.#..      Sample Output 1 1  For example, by walking to (2,2) and then using the magic to travel to (4,4) , just one use of magic is enough.  Note that he cannot walk diagonally.       Sample Input 2 4 4
1 4
4 1
.##.
####
####
.##.      Sample Output 2 -1  He cannot move from there.       Sample Input 3 4 4
2 2
3 3
....
....
....
....      Sample Output 3 0  No use of magic is needed.       Sample Input 4 4 5
1 2
2 5
#.###
####.
#..##
#..##      Sample Output 4 2

Solution (Python):

import sys
from collections import deque
from typing import List, Tuple


class WarpableMaze:
    __slots__ = ["height", "width", "is_unsearched", "is_unreachable", "dist"]

    def __init__(
        self, height: int, width: int, grid: List[bytes], road: str = ".",
    ) -> None:
        self.height = height + 4
        self.width = width + 4
        self.is_unsearched = 1 << 30
        self.is_unreachable = -1
        self.dist = self._convert_grid_to_dist(grid, road)

    def _convert_grid_to_dist(self, grid: List[bytes], road: str) -> List[int]:
        """Convert a 2D grid to a 1D dist."""
        dist = [self.is_unreachable] * self.height * self.width
        i = self.width * 2 + 1
        for row in grid:
            for c in row.decode():
                i += 1
                if c == road:
                    dist[i] = self.is_unsearched
            i += 4
        return dist

    def _flatten_coordinate(self, x: int, y: int) -> int:
        """Flatten 2D coordinate values.
        Values of a coordinate must be 1-origin.
        """
        return self.width * (x + 1) + y + 1

    def bfs(self, start_2d: Tuple[int, int], goal_2d: Tuple[int, int]) -> int:
        """BFS to compute the distance from start to goal.
        Values of start_2d and goal_2d must be 1-origin.
        """
        start = self._flatten_coordinate(*start_2d)
        goal = self._flatten_coordinate(*goal_2d)

        w = self.width
        walk_to_warp = {
            -w: (-2 * w - 2, -2 * w - 1, -2 * w, -2 * w + 1, -w - 1),
            w: (w + 1, 2 * w - 1, 2 * w, 2 * w + 1, 2 * w + 2),
            -1: (-w - 2, -2, w - 2, w - 1, 2 * w - 2),
            1: (-w + 1, -2 * w + 2, -w + 2, 2, w + 2),
        }

        dist = self.dist[:]
        dist[start] = 0
        queue = deque([start])
        while queue:
            x = queue.popleft()
            cur_dist = dist[x]
            if x == goal:
                break

            for walk, warp in walk_to_warp.items():
                nx = x + walk
                if dist[nx] > cur_dist:
                    dist[nx] = cur_dist
                    queue.appendleft(nx)
                    continue
                if dist[nx] >= 0:
                    continue

                for dx in warp:
                    nx = x + dx
                    if dist[nx] > cur_dist + 1:
                        dist[nx] = cur_dist + 1
                        queue.append(nx)

        return dist[goal] if dist[goal] != self.is_unsearched else self.is_unreachable


def main():
    read = sys.stdin.buffer.read
    readline = sys.stdin.buffer.readline

    H, W = map(int, readline().split())
    (*start,) = map(int, readline().split())
    (*goal,) = map(int, readline().split())
    (*S,) = read().split()

    maze = WarpableMaze(H, W, S)
    print(maze.bfs(start, goal))


if __name__ == "__main__":
    main()

Solution (Python):
from collections import*
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
d=eval('[-1]*w,input(),'*h)
q=deque([(s-1,t-1,0)])
while q:
 y,x,c=q.pop()
 if d[y+y][x]<0:
  for a in range(25):a,b=a//5-2,a%5-2;i=a+y;j=b+x;d[y+y][x]=c;h>i>-1<j<w!=d[i-~i][j]>'
print(d[f+f-2][g-1])

Solution (Python):
from collections import deque
def good(x,y):
    if (x>=0 and x<h) and (y>=0 and y<w):
        return (mat[x][y] != "
h, w = map(int,input().split())
sh, sw = map(int,input().split())
eh, ew = map(int,input().split())
mat = []
for _ in range(h):
    s = input()
    mat.append(s)
x = [1,-1,0,0]
y = [0,0,-1,1]
dist = [[float('inf') for i in range(w)]for j in range(h)]
sh -= 1
sw -= 1
eh -= 1
ew -= 1
dist[sh][sw] = 0
queue = deque()
queue.appendleft((sh,sw))
while queue:
    m = queue.popleft()
    for d in range(4):
        nx = m[0] + x[d]
        ny = m[1] + y[d]
        if good(nx,ny):
            if dist[nx][ny] > dist[m[0]][m[1]]:
                dist[nx][ny] =  dist[m[0]][m[1]]
                queue.appendleft((nx,ny))
    for i in range(m[0]-2,m[0]+3):
        for j in range(m[1]-2,m[1]+3):
            if good(i,j):
                if dist[i][j] > dist[m[0]][m[1]] + 1:
                    dist[i][j] = dist[m[0]][m[1]] + 1
                    queue.append((i,j))
if dist[eh][ew] == float('inf'):
    print(-1)
else:
    print(dist[eh][ew])

Solution (Python):
import zlib,base64
exec(zlib.decompress(base64.b85decode("c-l2k%Wi`(5WMphj;e}XSdx$`mw@vl76$_+EaG9nDM`P+j+!2JMw*?~Xtr6VK~z)Uo67Mtu7U?UEiMY6r40

Solution (Python):
from collections import*
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=zip(*eval('(input(),[-1]*w),'*h))
q=deque([(s-1,t-1,0)])
while q:
 y,x,c=q.pop()
 if d[y][x]<0:
  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]>'
print(d[f-1][g-1])

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=zip(*eval('(input(),[I]*w),'*h))
q=deque([(s-1,t-1,1)])
while q:
 y,x,c=q.pop()
 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]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=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]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=zip(*eval('(input(),[I]*w),'*h))
q=deque([(s-1,t-1,1)])
r=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]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
S = [list(input()) for _ in range(H)]

visited = [[-1] * W for _ in range(H)]

que = deque([(Ch-1, Cw-1, 0)])
move = ((1, 0), (-1, 0), (0, 1), (0, -1))
while que:
    ci, cj, d = que.popleft()

    if visited[ci][cj] != -1:
        continue
    visited[ci][cj] = d

    for di, dj in move:
        ni, nj = ci + di, cj + dj
        if not (0 <= ni < H and 0 <= nj < W) or visited[ni][nj] != -1:
            continue
        if S[ni][nj] == '.':
            que.appendleft((ni, nj, d))

    for di in range(-2, 3):
        for dj in range(-2, 3):
            ni, nj = ci+di, cj+dj
            if not (0 <= ni < H and 0 <= nj < W)  \
                    or visited[ni][nj] != -1:
                continue
            if S[ni][nj] == '.':
                que.append((ni, nj, d+1))
    
    

if visited[Dh-1][Dw-1] == -1:
    print(-1)
else:
    print(visited[Dh-1][Dw-1])

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=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 i in range(y-2,y+3):
   for j in range(x-2,x+3):d[y][x]=c;h>i>-1<j<w!=m[i][j]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=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 i in range(y-2,y+3):
   for j in range(x-2,x+3):d[y][x]=c;h>i>-1<j<w!=m[i][j]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=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 i in range(y-2,y+3):
   for j in range(x-2,x+3):d[y][x]=c;h>i>-1<j<w<d[i][j]!=m[i][j]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=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:
  d[y][x]=c
  for i in range(y-2,y+3):
   for j in range(x-2,x+3):h>i>-1<j<w<d[i][j]!=m[i][j]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import deque
h,w=map(int,input().split())
ch,cw=map(lambda x:int(x)-1,input().split())
dh,dw=map(lambda x:int(x)-1,input().split())
tizu=[]
d=deque()
d.appendleft([ch,cw])
cost=[[-1 for i in range(w)]for j in range(h)]
dx=[1,0,-1,0,-2,-2,-2,-2,-2,-1,-1,-1,-1,0,0,1,1,1,1,2,2,2,2,2]
dy=[0,1,0,-1,-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]
for i in range(h):
    tizu.append(input())
cost[ch][cw]=0
while(d):
    x,y=d.popleft()
    for i in range(4):
        nx=x+dx[i]
        ny=y+dy[i]
        
        if(nx<0 or ny<0 or nx>=h or ny>=w):
            continue
        if(cost[nx][ny]>-1 and cost[nx][ny]<=cost[x][y]):
            continue
        if(tizu[nx][ny]=='.'):
            cost[nx][ny]=cost[x][y]
            d.appendleft([nx,ny])
    
    for i in range(4,24):
        nx=x+dx[i]
        ny=y+dy[i]
        if(nx<0 or ny<0 or nx>=h or ny>=w):
            continue
        if(cost[nx][ny]>-1):
            continue
        if(tizu[nx][ny]=='.'):
            cost[nx][ny]=cost[x][y]+1
            d.append([nx,ny])

print(cost[dh][dw])

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=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:
  d[y][x]=c
  for i in range(y-2,y+3):
   for j in range(x-2,x+3):h>i>-1<j<w<I==d[i][j]!=m[i][j]>'
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m,d=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:
  d[y][x]=c
  for i in range(y-2,y+3):
   for j in range(x-2,x+3):
    if h>i>-1<j<w<I==d[i][j]!=m[i][j]>'
     if abs(y-i)+abs(x-j)<2:q.appendleft((i,j,c))
     else:q.append((i,j,c+1))
print(d[f-1][g-1]%I-1)

Solution (Python):
from collections import*
e=eval
I=9**9
(h,w),(s,t),(f,g)=e('map(int,input().split()),'*3)
m=e('input(),'*h)
d=e('[I]*w,'*h)
q=deque([(s-1,t-1,1)])
while q:
 y,x,c=q.popleft()
 if d[y][x]>c:
  d[y][x]=c
  for i in range(y-2,y+3):
   for j in range(x-2,x+3):
    if h>i>-1<j<w<I==d[i][j]!=m[i][j]>'
     if abs(y-i)+abs(x-j)<2:q.appendleft((i,j,c))
     else:q.append((i,j,c+1))
print(d[f-1][g-1]%I-1)

Solution (Python):
INF=10**6
f=lambda:map(int,input().split())
h,w=f()
ch,cw=f()
dh,dw=f()
g=[input() for _ in range(h)]
d=[[INF]*w for _ in range(h)]
from collections import *
q=deque([(0,ch-1,cw-1)])
while q:
  c,x,y=q.popleft()
  if d[x][y]<=c: continue
  d[x][y]=c
  for dx in range(-2,3):
    for dy in range(-2,3):
      j=abs(dx)+abs(dy)
      nx,ny=x+dx,y+dy
      if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and j:
        if j>1: q.append((c+1,nx,ny))
        else: q.appendleft((c,nx,ny))
a=d[dh-1][dw-1]
print([-1,a][a<INF])

Solution (Python):
INF=10**6
f=lambda:map(int,input().split())
h,w=f()
ch,cw=f()
dh,dw=f()
ch-=1
cw-=1
dh-=1
dw-=1
g=[input() for _ in range(h)]
from collections import *
d=[[INF]*w for _ in range(h)]
q=deque([(0,ch,cw)])
while q:
  td,tx,ty=q.popleft()
  if d[tx][ty]<=td: continue
  d[tx][ty]=td
  for dx,dy in [(1,0),(0,1),(-1,0),(0,-1)]:
    nx,ny=tx+dx,ty+dy
    if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.':
      q.appendleft((td,nx,ny))
  for dx in range(-2,3):
    for dy in range(-2,3):
      nx,ny=tx+dx,ty+dy
      if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.':
        q.append((td+1,nx,ny))
a=d[dh][dw]
print([-1,a][a<INF])

Solution (Python):
from collections import*
I=9**9
(h,w),(s,t),(f,g)=eval('map(int,input().split()),'*3)
m=[input()for _ in range(h)]
d=[w*[I]for _ in m]
q=deque([(s-1,t-1,1)])
while q:
  y,x,c=q.popleft()
  if d[y][x]<I:continue
  d[y][x]=c
  for i in range(y-2,y+3):
    for j in range(x-2,x+3):
      if h>i>-1<j<w<I==d[i][j]!=m[i][j]>'
        if abs(y-i)+abs(x-j)<2:q.appendleft((i,j,c))
        else:q.append((i,j,c+1))
print(d[f-1][g-1]%I-1)

Solution (Python):
f=lambda:map(int,input().split())
h,w=f()
ch,cw=f()
dh,dw=f()
g=[[*input()] for _ in range(h)]
from collections import *
q=deque([(0,ch-1,cw-1)])
while q:
  d,x,y=q.popleft()
  if g[x][y]!='.': continue
  g[x][y]=d
  for dx in range(-2,3):
    for dy in range(-2,3):
      j=abs(dx)+abs(dy)
      nx,ny=x+dx,y+dy
      if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and j:
        if j>1: q.append((d+1,nx,ny))
        else: q.appendleft((d,nx,ny))
a=g[dh-1][dw-1]
print([a,-1][a=='.'])

Solution (Python):
from collections import deque
import copy

h,w=map(int,input().split())
cy,cx=map(int,input().split())
gy,gx=map(int,input().split())
inf=float('inf')
maze=[]
for _ in range(h):
  s=list(input())
  for i in range(w):
    if s[i]=='.':
      s[i]=inf
  maze.append(s)
  
def solve(maze,cy,cx,gy,gx):
  maze1=copy.deepcopy(maze)
  [sy,sx]=[cy-1,cx-1]
  qu=deque([[sy,sx]])
  maze[sy][sx]=0
  T=0
  while qu:
    y,x=qu.popleft()
    t=maze[y][x]
    
    if maze1[y][x]!=1:
      
      for i in ([1,0],[0,1],[-1,0],[0,-1]):
        ny=y-i[0]
        nx=x-i[1]
        if 0<=ny<=h-1 and 0<=nx<=w-1 and maze[ny][nx]!='
          if maze[ny][nx]>t:
            maze[ny][nx]=t
            qu.appendleft([ny,nx])
          
      
      for j in range(-2,3):
        for k in range(-2,3):
          ny=y-j
          nx=x-k
          if 0<=ny<=h-1 and 0<=nx<=w-1 and maze[ny][nx]!='
            if maze[ny][nx]>t:
              maze[ny][nx]=t+1
              qu.append([ny,nx])
      maze1[y][x]=1
            
  return maze[gy-1][gx-1]
  
if solve(maze,cy,cx,gy,gx)==inf:
  print(-1)
  
else:
  print(solve(maze,cy,cx,gy,gx))

Solution (Python):
from collections import deque
import sys

























def BFS(task, ct):
  D = [(1,0), (0,1), (-1,0), (0,-1)] 
  semi_visited = set() 
  task_n = deque([]) 
  
  for s in task: 
    semi_visited.add(s)
    
  while task: 
    s = task.popleft() 
    if s == (hg, wg): 
      print(ct)
      sys.exit()
    x = s[0]
    y = s[1]
    for d in D:
      s_n = (x+d[0], y+d[1]) 
      if 0 <= s_n[0] <= H-1 and 0 <= s_n[1] <= W-1:
        if (s_n not in semi_visited) and S[s_n[0]][s_n[1]] == ".": 
          
          task.append(s_n) 
          semi_visited.add(s_n) 
          visited.add(s_n)  
          
  for s in semi_visited: 
    warp(s, task_n) 
  
  return (ct+1, task_n) 



def warp(p, task_n): 
  x = p[0]
  y = p[1]
  for dh in range(-2,3):   
    for dw in range(-2,3):
      s_n = (x+dh, y+dw)
      if 0 <= s_n[0] <= H-1 and 0 <= s_n[1] <= W-1:
        if s_n not in visited and S[s_n[0]][s_n[1]] == ".": 
          
          task_n.append(s_n) 
          visited.add(s_n)   


H, W = map(int, input().split())
hs, ws = map(int, input().split())
hs -= 1
ws -= 1
hg, wg = map(int, input().split())
hg -= 1
wg -= 1

S = [input() for _ in range(H)]

task = deque([(hs, ws)]) 
visited = {(hs, ws)} 
ct = 0

while task: 
  ct, task = BFS(task, ct) 
  

print(-1)

Solution (Python):
INF=10**6
f=lambda:map(int,input().split())
h,w=f()
ch,cw=f()
dh,dw=f()
g=[input() for _ in range(h)]
d=[[INF]*w for _ in range(h)]
d[ch-1][cw-1]=0
from collections import *
q=deque([(0,ch-1,cw-1)])
while q:
  td,tx,ty=q.popleft()
  if d[tx][ty]<td: continue
  for dx,dy in [(1,0),(0,1),(-1,0),(0,-1)]:
    nx,ny=tx+dx,ty+dy
    if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and d[nx][ny]>td:
      d[nx][ny]=td
      q.appendleft((td,nx,ny))
  for dx in range(-2,3):
    for dy in range(-2,3):
      nx,ny=tx+dx,ty+dy
      if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and d[nx][ny]>td+1:
        d[nx][ny]=td+1
        q.append((td+1,nx,ny))
a=d[dh-1][dw-1]
print([-1,a][a<INF])

Solution (Python):
import os
import sys

import numpy as np
from heapq import heappop, heappush


def solve(h, w, s, t, field):
    WARP = (-(w * 2 + 10), -(w * 2 + 9), -(w * 2 + 8), -(w * 2 + 7), -(w * 2 + 6),
            -(w + 6), -(w + 5), -(w + 3), -(w + 2),
            -2, 2,
            w + 2, w + 3, w + 5, w + 6,
            w * 2 + 6, w * 2 + 7, w * 2 + 8, w * 2 + 9, w * 2 + 10)
    WALK = (-(w + 4), -1, 1, w + 4)

    qc = np.zeros(2000000, dtype=np.int32)
    qv = np.zeros(2000000, dtype=np.int32)
    qv[0] = s
    l, r = 0, 1
    visited = np.zeros((h + 4) * (w + 4), np.int8)
    queued = np.zeros((h + 4) * (w + 4), np.int8)
    queued[s] = 1
    while l < r:
        cost = qc[l]
        v = qv[l]
        l += 1
        if v == t:
            return cost
        if visited[v]:
            continue
        visited[v] = 1
        for d in WALK:
            u = v + d
            if field[u] or visited[u] or queued[u]:
                continue
            queued[u] = 1
            l -= 1
            qc[l] = cost
            qv[l] = u
        for d in WARP:
            u = v + d
            if field[u] or visited[u] or queued[u]:
                continue
            qc[r] = cost + 1
            qv[r] = u
            r += 1

    return -1


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8,i8,i8,i8,i1[:],)')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8,i8,i8,i8,i1[:],)', cache=True)(solve)
    print('compiled', file=sys.stderr)

h, w = map(int, sys.stdin.readline().split())
ch, cw = map(int, sys.stdin.readline().split())
dh, dw = map(int, sys.stdin.readline().split())
field = np.ones((h + 4) * (w + 4), dtype=np.int8)
for i in range(h):
    line = sys.stdin.readline().strip()
    field[(i + 2) * (w + 4) + 2:(i + 2) * (w + 4) + w + 2] = list(map('.
s = (ch + 1) * (w + 4) + cw + 1
t = (dh + 1) * (w + 4) + dw + 1
ans = solve(h, w, s, t, field)
print(ans)

Solution (Python):
INF=10**6
f=lambda:map(int,input().split())
h,w=f()
ch,cw=f()
ch-=1
cw-=1
dh,dw=f()
dh-=1
dw-=1
g=[input() for _ in range(h)]
from collections import *
def grid_01_bfs(x,y):
  d=[[INF]*w for _ in range(h)]
  d[x][y]=0
  q=deque([(0,x,y)])
  while q:
    td,tx,ty=q.popleft()
    if d[tx][ty]<td: continue
    for dx,dy in [(1,0),(0,1),(-1,0),(0,-1)]:
      nx,ny=tx+dx,ty+dy
      if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and d[nx][ny]>td:
        d[nx][ny]=td
        q.appendleft((d[nx][ny],nx,ny))
    for dx in range(-2,3):
      for dy in range(-2,3):
        nx,ny=tx+dx,ty+dy
        if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and d[nx][ny]>td+1:
          d[nx][ny]=td+1
          q.append((d[nx][ny],nx,ny))
  return d
a=grid_01_bfs(ch,cw)[dh][dw]
print([-1,a][a<INF])

Solution (Python):
import os
import sys

import numpy as np
from heapq import heappop, heappush


def solve(h, w, s, t, field):
    WARP = (-(w * 2 + 10), -(w * 2 + 9), -(w * 2 + 8), -(w * 2 + 7), -(w * 2 + 6),
            -(w + 6), -(w + 5), -(w + 3), -(w + 2),
            -2, 2,
            w + 2, w + 3, w + 5, w + 6,
            w * 2 + 6, w * 2 + 7, w * 2 + 8, w * 2 + 9, w * 2 + 10)
    WALK = (-(w + 4), -1, 1, w + 4)

    q = [(0, s)]
    visited = np.zeros((h + 4) * (w + 4), np.int8)
    queued = np.zeros((h + 4) * (w + 4), np.int8)
    queued[s] = 1
    while q:
        cost, v = heappop(q)
        if v == t:
            return cost
        if visited[v]:
            continue
        visited[v] = 1
        for d in WALK:
            u = v + d
            if field[u] or visited[u] or queued[u]:
                continue
            queued[u] = 1
            heappush(q, (cost, u))
        for d in WARP:
            u = v + d
            if field[u] or visited[u] or queued[u]:
                continue
            heappush(q, (cost + 1, u))

    return -1


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8,i8,i8,i8,i1[:],)')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8,i8,i8,i8,i1[:],)', cache=True)(solve)
    print('compiled', file=sys.stderr)

h, w = map(int, sys.stdin.readline().split())
ch, cw = map(int, sys.stdin.readline().split())
dh, dw = map(int, sys.stdin.readline().split())
field = np.ones((h + 4) * (w + 4), dtype=np.int8)
for i in range(h):
    line = sys.stdin.readline().strip()
    field[(i + 2) * (w + 4) + 2:(i + 2) * (w + 4) + w + 2] = list(map('.
s = (ch + 1) * (w + 4) + cw + 1
t = (dh + 1) * (w + 4) + dw + 1
ans = solve(h, w, s, t, field)
print(ans)

Solution (Python):
from collections import deque
HW = input().split()
H, W = int(HW[0]), int(HW[1])
C = input().split()
Ch, Cw = int(C[0]), int(C[1])
D = input().split()
Dh, Dw = int(D[0]), int(D[1])
route = []
for h in range(H):
    route.append(input())

visited = [[False]*W for x in range(H)]
kouho = deque()
kouho.append([Ch-1, Cw-1])
warpkouho = deque()

def check_walk(a, b):
    if 0 <= a <= H-1 and 0 <= b <= W-1: 
        if visited[a][b] == False and route[a][b] == ".":
            kouho.append([a, b])
def check_warp(a, b, cwarp):
    if 0 <= a <= H-1 and 0 <= b <= W-1:
        if visited[a][b] == False and route[a][b] == ".":
            warpkouho.append([a, b, cwarp+1])

def wizard():
    warp = 1
    while True:
        if len(kouho) != 0:
            tmp = kouho.popleft()
        elif len(warpkouho) != 0:
            tmp = warpkouho.popleft()
            warp = tmp[2]
        else:
            break
        h = tmp[0]
        w = tmp[1]
        if visited[h][w] == False:
            visited[h][w] = warp
            check_walk(h-1, w)
            check_walk(h+1, w)
            check_walk(h, w-1)
            check_walk(h, w+1)
            for n in range(5):
                for m in range(5):
                  check_warp(h-2+n, w-2+m, warp)
        if h == Dh-1 and w == Dw-1:
            print(visited[h][w]-1)
            return
    print(-1)
wizard()

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
dh,dw=nii()
s=[list(input()) for i in range(h)]

ch-=1
cw-=1
dh-=1
dw-=1

ans=[[-1]*w for i in range(h)]
ans[ch][cw]=0

que=deque()
que.append((ch,cw))

while que:
  y,x=que.popleft()

  if y==dh and x==dw:
    print(ans[y][x])
    exit()

  for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
    ny=y+dy
    nx=x+dx
    if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
      que.appendleft((ny,nx))
      s[ny][nx]='
      ans[ny][nx]=ans[y][x]

  for i in range(-2,3):
    for j in range(-2,3):
      ny=y+i
      nx=x+j
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.append((ny,nx))
        ans[ny][nx]=ans[y][x]+1

print(-1)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
dh,dw=nii()
s=[list(input()) for i in range(h)]

ch-=1
cw-=1
dh-=1
dw-=1

dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0

que=deque()
que.append((ch,cw))

def BFS():
  while que:
    y,x=que.popleft()

    if y==dh and x==dw:
      print(dist[y][x])
      exit()

    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.appendleft((ny,nx))
        s[ny][nx]='
        dist[ny][nx]=dist[y][x]

    for i in range(-2,3):
      for j in range(-2,3):
        ny=y+i
        nx=x+j
        if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
          que.append((ny,nx))
          dist[ny][nx]=dist[y][x]+1

BFS()

print(-1)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
dh,dw=nii()
s=[list(input()) for i in range(h)]

ch-=1
cw-=1
dh-=1
dw-=1

dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0

que=deque()
que.append((ch,cw))

def BFS(que):
  while que:
    y,x=que.popleft()

    if y==dh and x==dw:
      print(dist[y][x])
      exit()

    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.appendleft((ny,nx))
        s[ny][nx]='
        dist[ny][nx]=dist[y][x]

    for i in range(-2,3):
      for j in range(-2,3):
        ny=y+i
        nx=x+j
        if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
          que.append((ny,nx))
          dist[ny][nx]=dist[y][x]+1

BFS(que)

print(-1)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
dh,dw=nii()
s=[list(input()) for i in range(h)]

ch-=1
cw-=1
dh-=1
dw-=1

ans=[[-1]*w for i in range(h)]
ans[ch][cw]=0

que=deque()
que.append((ch,cw))

def BFS():
  while que:
    y,x=que.popleft()

    if y==dh and x==dw:
      print(ans[y][x])
      exit()

    for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.appendleft((ny,nx))
        s[ny][nx]='
        ans[ny][nx]=ans[y][x]

      for i in range(-2,3):
        for j in range(-2,3):
          ny=y+i
          nx=x+j
          if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
            que.append((ny,nx))
            ans[ny][nx]=ans[y][x]+1

BFS()

print(-1)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
dh,dw=nii()
s=[list(input()) for i in range(h)]

ch-=1
cw-=1
dh-=1
dw-=1

ans=[[-1 for i in range(w)] for i in range(h)]
ans[ch][cw]=0

que=deque()
que.append((ch,cw))

def BFS():
  while que:
    y,x=que.popleft()

    if y==dh and x==dw:
      print(ans[y][x])
      exit()

    for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.appendleft((ny,nx))
        s[ny][nx]='
        ans[ny][nx]=ans[y][x]

      for i in range(-2,3):
        for j in range(-2,3):
          ny=y+i
          nx=x+j
          if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
            que.append((ny,nx))
            ans[ny][nx]=ans[y][x]+1

BFS()

print(-1)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
ch-=1
cw-=1
dh,dw=nii()
dh-=1
dw-=1
s=[list(input()) for i in range(h)]

dist=[[-1]*w for i in range(h)]

def BFS(que):
  while que:
    y,x=que.popleft()

    if y==dh and x==dw:
      print(dist[y][x])
      exit()

    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.appendleft((ny,nx))
        s[ny][nx]='
        dist[ny][nx]=dist[y][x]

    for i in range(-2,3):
      for j in range(-2,3):
        ny=y+i
        nx=x+j
        if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
          que.append((ny,nx))
          dist[ny][nx]=dist[y][x]+1

dist[ch][cw]=0

que=deque()
que.append((ch,cw))

BFS(que)

print(-1)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
ch-=1
cw-=1
dh,dw=nii()
dh-=1
dw-=1
s=[list(input()) for i in range(h)]

dist=[[-1]*w for i in range(h)]

def BFS(que):
  while que:
    y,x=que.popleft()

    if y==dh and x==dw:
      print(dist[y][x])
      exit()

    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.appendleft((ny,nx))
        s[ny][nx]='
        dist[ny][nx]=dist[y][x]
    for dy,dx in [[-2,-2],[-2,-1],[-2,0],[-2,1],[-2,2],\
                  [-1,-2],[-1,-1],[-1,1],[-1,2],\
                  [0,-2],[0,2],\
                  [1,-2],[1,-1],[1,1],[1,2],\
                  [2,-2],[2,-1],[2,0],[2,1],[2,2]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
        que.append((ny,nx))
        dist[ny][nx]=dist[y][x]+1

dist[ch][cw]=0

que=deque()
que.append((ch,cw))

BFS(que)

print(-1)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
dh,dw=nii()
s=[list(input()) for i in range(h)]

ch-=1
cw-=1
dh-=1
dw-=1

ans=[[-1 for i in range(w)] for i in range(h)]
ans[ch][cw]=0

que=deque()
que.append((ch,cw))

while que:
  y,x=que.popleft()

  if y==dh and x==dw:
    print(ans[y][x])
    exit()

  for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
    ny=y+dy
    nx=x+dx
    if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
      que.appendleft((ny,nx))
      s[ny][nx]='
      ans[ny][nx]=ans[y][x]

    for i in range(-2,3):
      for j in range(-2,3):
        ny=y+i
        nx=x+j
        if 0<=ny<h and 0<=nx<w and s[ny][nx]!='
          que.append((ny,nx))
          ans[ny][nx]=ans[y][x]+1

print(-1)

Solution (Python):
def d_wizard_in_maze():
    from collections import deque
    H, W = [int(i) for i in input().split()]
    Start_row, Start_col = [int(i) - 1 for i in input().split()]
    Goal_row, Goal_col = [int(i) - 1 for i in input().split()]
    Grid = [input() for _ in range(H)]

    warp_count = [[-1] * W for i in range(H)]
    neighbor_4 = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    neighbor_25 = [(i, j) for i in range(-2, 3) for j in range(-2, 3)]
    queue = deque([(Start_row, Start_col, 0)])  

    while(queue):
        row, col, count = queue.popleft()
        if warp_count[row][col] != -1:
            continue
        warp_count[row][col] = count

        for dr, dc in neighbor_4:
            nr, nc = row + dr, col + dc
            if 0 <= nr < H and 0 <= nc < W and Grid[nr][nc] == '.':
                if warp_count[nr][nc] == -1:
                    queue.appendleft((nr, nc, count))

        for dr, dc in neighbor_25:
            nr, nc = row + dr, col + dc
            if 0 <= nr < H and 0 <= nc < W and Grid[nr][nc] == '.':
                queue.append((nr, nc, count + 1))

    return warp_count[Goal_row][Goal_col]

print(d_wizard_in_maze())