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
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


import numpy as np
from numba import njit, b1, i4, i8, f8
from heapq import heappop as hpp, heappush as hp

h,w = map(int, input().split())
ch,cw = map(int, input().split())
dh,dw = map(int, input().split())
ch -= 1
cw -= 1
dh -= 1
dw -= 1
rows,cols = h,w

OK = "."
NG = "

ss = np.array([[c=="
inf = 1<<30
@njit((b1[:, :],i8,i8,i8,i8), cache=True)
def main(ss,ch,cw,dh,dw):
    start = ch*w+cw
    goal = dh*w+dw
    n = h*w
    seen = np.full(n, inf, np.int64)
    seen[start] = 0
    q = [(0, start)] 
    
    
    dx = []
    dy = []
    vvs = []
    for i in range(-2,3):
        for j in range(-2,3):
            if not (i==j==0):
                dx.append(i)
                dy.append(j)
                if abs(i)+abs(j)>1:
                    vvs.append(1)
                else:
                    vvs.append(0)
    while q:

        pnum,pu = hpp(q)
        ux,uy = divmod(pu,w)
        
        if pu==goal:
            break
        for xx,yy,vv in zip(dx,dy,vvs):
    
    
            x,y = ux+xx, uy+yy
            u = x*w + y
            num = pnum+vv
            if x<0 or y<0 or x>=h or y>=w or ss[x][y]:
                continue
    
            if seen[u]>num:
                seen[u] = num
                hp(q,(num, u))
                
    val = seen[goal]
    if val==inf:
        return -1
    else:
        return val
print(main(ss,ch,cw,dh,dw))

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque

H,W=map(int,input().split())
sh,sw=map(int,input().split())
gh,gw=map(int,input().split())
MAP=[input().strip() for i in range(H)]

ANS=[[1<<30]*W for i in range(H)]

sh-=1
sw-=1
gh-=1
gw-=1

ANS[sh][sw]=0

Q=deque([(sh,sw)])

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

    for i in range(x-2,x+3):
        if 0<=i<H:           
            for j in range(y-2,y+3):
                if 0<=j<W:                
                    if MAP[i][j]=="." and abs(i-x)+abs(j-y)==1 and ANS[i][j]>ANS[x][y]:
                        ANS[i][j]=ANS[x][y]
                        Q.appendleft((i,j))
                    elif MAP[i][j]=="." and abs(i-x)+abs(j-y)>1 and ANS[i][j]>ANS[x][y]+1:
                        ANS[i][j]=ANS[x][y]+1
                        Q.append((i,j))

if ANS[gh][gw]==1<<30:
    print(-1)
else:
    print(ANS[gh][gw])

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())
S = [list(input()) for _ in range(H)]
dist = [[-1] * W for _ in range(H)]

q = deque()
q.append((0, ch, cw))
while q:
    c, h, w = q.popleft()
    if dist[h][w] >= 0:
        continue
    dist[h][w] = c
    for hh in range(-2, 3):
        for ww in range(-2, 3):
            if 0 <= h+hh < H and 0 <= w+ww < W and S[h+hh][w+ww] == "." and dist[h+hh][w+ww] < 0:
                if (hh, ww) in ((0,1), (1,0), (-1,0), (0,-1)):
                    q.appendleft((c, h+hh, w+ww)) 
                else:
                    q.append((c+1, h+hh, w+ww)) 

print(dist[dh][dw])

Solution (Python):
import sys
from collections import deque
H, W = map(int, input().split())
c = [int(i) + 1 for i in input().split()]
d = [int(i) + 1 for i in input().split()]

s = []
s.append('
s.append('
for i in range(H):
    a = input()
    s.append('
s.append('
s.append('

q = deque([]) 
qq = deque([])
q.append((c[0], c[1], 0))
visited = [[False for __ in range(W+4)] for _ in range(H+4)]

while q:
    xx, yy, kaisuu = q.popleft()
    if visited[xx][yy] == True:
        continue
    qq.append((xx, yy))
    ls = deque()
    while qq:
        x, y = qq.pop()
        visited[x][y] = True
        ls.append((x, y, kaisuu))
        if x == d[0] and y == d[1]:
            print(kaisuu)
            sys.exit()
        if s[x+1][y] == '.' and visited[x+1][y] == False:
            qq.append((x+1, y))
        if s[x-1][y] == '.' and visited[x-1][y] == False:
            qq.append((x-1, y))
        if s[x][y+1] == '.' and visited[x][y+1] == False:
            qq.append((x, y+1))
        if s[x][y-1] == '.' and visited[x][y-1] == False:
            qq.append((x, y-1))
    for u in ls:
        a, b, e = u
        for i in range(-2, 3):
            for j in range(-2, 3):
                if i == 0 and j == 0:
                    continue
                if abs(i) == 1 and abs(j) == 0:
                    continue
                if abs(j) == 1 and abs(i) == 0:
                    continue
                if s[a+i][b+j] == '.' and visited[a+i][b+j] == False:
                    q.append((a+i, b+j, e+1))
print(-1)

Solution (Python):
max2 = lambda x,y: x if x > y else y
min2 = lambda x,y: x if x < y else y

import sys
from itertools import count
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline


MOVES = [
    ((1, 0), [(2,-1),(2,0),(2,1),(2,2),(1,1)]),
    ((-1, 0),[(-2,-1),(-2,0),(-2,1),(-2,-2),(-1,-1)]),
    ((0, 1), [(1,2),(0,2),(-1,2),(-2,2),(-1,1)]),
    ((0, -1), [(1,-2),(0,-2),(-1,-2),(2,-2),(1,-1)]),
    ]

CONVERTED_MOVES = None

def solve(dist, start, goal):
    q = [start]
    cnt = 0
    while q:
        nq = []
        while q:
            x = q.pop()
            if x == goal:
                return cnt
            if dist[x] < cnt:
                continue
            for d,l in CONVERTED_MOVES:
                nx = x+d
                if dist[nx] > cnt:
                    dist[nx] = cnt
                    q.append(nx)
                if dist[nx] < 0:
                    for t in l:
                        p = x+t
                        if dist[p] > cnt+1:
                            dist[p] = cnt+1
                            nq.append(p)
        q = nq
        cnt += 1

    return -1




if __name__ == '__main__':
    H,W = map(int,readline().split())
    start = tuple(map(lambda i:int(i)+1,readline().split()))
    goal = tuple(map(lambda i:int(i)+1,readline().split()))

    H += 4
    W += 4

    dist = [-1]*(W*H)

    start = start[0]*W+start[1]
    goal = goal[0]*W+goal[1]

    for t,s in zip(count(2*W,W),read().split()):
        for i,c in zip(count(t+2),s.decode()):
            if c == '.':
                dist[i] = 10**7

    convert = lambda x,y: x*W+y
    CONVERTED_MOVES = []
    for d,l in MOVES:
        d = convert(*d)
        l = [convert(*d) for d in l]
        CONVERTED_MOVES.append((d,l))

    

    print(solve(dist,start,goal))

Solution (Python):
from collections import deque

h, w = (int(x) for x in input().split())
ch, cw = (int(x) - 1 for x in input().split())
dh, dw = (int(x) - 1 for x in input().split())
s = [list(input()) for _ in range(h)]
d = [[-1] * w for _ in range(h)]
d[ch][cw] = 0
walk = [[0, 1], [0, -1], [1, 0], [-1, 0]]
warp = [[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]]

que = deque([[0, ch, cw]])
while que:
    count, y, x = que.popleft()
    if d[y][x] < count:
        continue
    for NY, NX in walk:
        if 0 <= y + NY < h and 0 <= x + NX < w and s[y + NY][x + NX] != '
            if d[y + NY][x + NX] == -1 or d[y + NY][x + NX] > count:
                d[y + NY][x + NX] = count
                que.appendleft([count, y + NY, x + NX])
    for NY, NX in warp:
        if 0 <= y + NY < h and 0 <= x + NX < w and s[y + NY][x + NX] != '
            if d[y + NY][x + NX] == -1 or d[y + NY][x + NX] > count + 1:
                d[y + NY][x + NX] = count + 1
                que.append([count + 1, y + NY, x + NX])

print(d[dh][dw])

Solution (Python):
import sys
input = sys.stdin.readline
from collections import deque

H,W=map(int,input().split())
sh,sw=map(int,input().split())
gh,gw=map(int,input().split())
MAP=[input().strip() for i in range(H)]

ANS=[[1<<30]*W for i in range(H)]

sh-=1
sw-=1
gh-=1
gw-=1

ANS[sh][sw]=0

Q=deque([(sh,sw)])

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

    for i,j in [(x-2,y-2),(x-2,y-1),(x-2,y),(x-2,y+1),(x-2,y+2),(x-1,y-2),(x-1,y-1),(x-1,y),(x-1,y+1),(x-1,y+2),(x,y-2),(x,y-1),(x,y+1),(x,y+2),(x+1,y-2),(x+1,y-1),(x+1,y),(x+1,y+1),(x+1,y+2),(x+2,y-2),(x+2,y-1),(x+2,y),(x+2,y+1),(x+2,y+2)]:
        if 0<=i<H and 0<=j<W:
            if MAP[i][j]=="." and abs(i-x)+abs(j-y)==1 and ANS[i][j]>ANS[x][y]:
                ANS[i][j]=ANS[x][y]
                Q.appendleft((i,j))
            elif MAP[i][j]=="." and abs(i-x)+abs(j-y)>1 and ANS[i][j]>ANS[x][y]+1:
                ANS[i][j]=ANS[x][y]+1
                Q.append((i,j))

if ANS[gh][gw]==1<<30:
    print(-1)
else:
    print(ANS[gh][gw])

Solution (Python):
from collections import deque

H, W = [int(_) for _ in input().split()]
C = [int(_) - 1 for _ in input().split()]
D = [int(_) - 1 for _ in input().split()]

S = [input() for _ in range(H)]
V = [[-1 for w in range(W)] for h in range(H)]

V[C[0]][C[1]] = 0

pool = deque()
pool.append(tuple([0, C[0], C[1]]))
while(pool):
    c, y, x = pool.popleft()
    if c != V[y][x]:
        continue
    for dx in [-2, -1, 0, 1, 2]:
        for dy in [-2, -1, 0, 1, 2]:
            if y + dy < 0 or H <= y + dy:
                continue
            if x + dx < 0 or W <= x + dx:
                continue
            if S[y+dy][x+dx] == "
                continue
            if (dx, dy) in [(-1,0),(1,0),(0,-1),(0,1)]:
                if V[y+dy][x+dx] == -1 or V[y+dy][x+dx] > V[y][x]:
                    V[y+dy][x+dx] = V[y][x]
                    pool.appendleft((c, y+dy, x+dx))
            elif V[y+dy][x+dx] == -1 or V[y+dy][x+dx] > V[y][x] + 1:
                V[y+dy][x+dx] = V[y][x] + 1
                pool.append((c+1, y+dy, x+dx))
print(V[D[0]][D[1]])

Solution (Python):
import sys
input = sys.stdin.readline
INF = float('inf')

def dijkstra_al(s, n, ALcost):
    '''
    n: 頂点の数、s: 始点
    AL_cost[head] = [(tail, cost), ..., (tail, cost)]
    cost存在しないときはinf
    '''
    import heapq

    fixed = [False] * n 
    nfixed = 0 
    vertex_cost = [INF] * n  

    
    vertex_cost[s] = 0
    H = []  
    heapq.heappush(H, (0, s))

    while(H): 
        
        u_cost, u = heapq.heappop(H)
        if fixed[u]: continue  
        fixed[u] = True
        nfixed += 1

        
        
        for v, cost in ALcost[u]:
            if fixed[v]: continue
            newcost = u_cost + cost
            if newcost < vertex_cost[v]:
                vertex_cost[v] = newcost
                heapq.heappush(H, (newcost, v))

        
        if nfixed == n: break

    return vertex_cost


def rc_to_v(y, x):
    return y * W + x

H, W = [int(x) for x in input().split()]
sy, sx = [int(x) - 1 for x in input().split()]
gy, gx = [int(x) - 1 for x in input().split()]
S = [list(input().strip()) for _ in range(H)]

AL = [[] for _ in range(H * W)]

for y in range(H):
    for x in range(W):
        if S[y][x] == '

        for dy in range(-2, 3):
            for dx in range(-2, 3):
                ny = y + dy
                nx = x + dx
                if ny < 0 or H <= ny or nx < 0 or W <= nx:
                    continue
                if S[ny][nx] == '
                    continue
                if (dy, dx) in [(0, -1), (0, 1), (1, 0), (-1, 0)]:
                    AL[rc_to_v(y, x)].append((rc_to_v(ny, nx), 0))
                else:
                    AL[rc_to_v(y, x)].append((rc_to_v(ny, nx), 1))


cost = dijkstra_al(rc_to_v(sy, sx), H * W, AL)

ans = cost[rc_to_v(gy, gx)]
print(-1 if ans == INF else int(ans))

Solution (Python):
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

def p(arr):
	print("_______________________")
	for i in arr:
		for j in i:
			print(j,end=" ")
		print()

h,w = readInts()
ch,cw = readInts()
dh,dw = readInts()
s = [["

q = deque()
visited = [[-1]*(w+2) for i in range(h+2)]
count = (w+2)*(h+2)
for i in range(h+2):
	for j in range(w+2):
		if s[i][j]=="
			visited[i][j] = float("inf")
			count -= 1

from pprint import pprint
visited[ch][cw] = 0

q = {(ch,cw)}
set_list = set()
cost = 0
while count:
	while len(q) !=0:
		x,y = q.pop()
		set_list.add((x,y))
		visited[x][y] = cost
		count-=1
		if s[x-1][y]=="." and visited[x-1][y]==-1:
			q.add((x-1,y))
		if s[x][y-1]=="." and visited[x][y-1]==-1:
			q.add((x,y-1))
		if s[x+1][y]=="." and visited[x+1][y]==-1:
			q.add((x+1,y))
		if s[x][y+1]=="." and visited[x][y+1]==-1:
			q.add((x,y+1))

	if len(set_list)==0:
		break

	cost+=1
	while len(set_list) != 0:
		x,y = set_list.pop()
		for dx in range(-2,3):
			for dy in range(-2,3):
				x2 = x+dx
				y2 = y+dy
				if visited[min(x2,h+1)][min(y2,w+1)]!=-1: continue
				q.add((x2,y2))

print(visited[dh][dw])

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)]

Ch, Cw = Ch - 1, Cw - 1
Dh, Dw = Dh - 1, Dw - 1
d = [[-1] * w for _ in range(h)]
d[Ch][Cw] = 0
walk = [[0, 1], [0, -1], [1, 0], [-1, 0]]
warp = [[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]]

que = deque([[0, Ch, Cw]])
while que:
    count, y, x = que.popleft()
    if d[y][x] < count:
        continue
    for NY, NX in walk:
        if 0 <= y + NY < h and 0 <= x + NX < w and s[y + NY][x + NX] != '
            if d[y + NY][x + NX] == -1 or d[y + NY][x + NX] > count:
                d[y + NY][x + NX] = count
                que.appendleft([count, y + NY, x + NX])
    for NY, NX in warp:
        if 0 <= y + NY < h and 0 <= x + NX < w and s[y + NY][x + NX] != '
            if d[y + NY][x + NX] == -1 or d[y + NY][x + NX] > count + 1:
                d[y + NY][x + NX] = count + 1
                que.append([count + 1, y + NY, x + NX])

print(d[Dh][Dw])

Solution (Python):
H,W = map(int,input().split())
Ch,Cw = map(int,input().split())
Dh,Dw = map(int,input().split())
S = [list(input()) for i in range(H)]
 
res_S = [[-1]*W for i in range(H)]
dx = [1,-1,0,0]
ddx = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]
dy = [0,0,1,-1]
ddy = [-2,-2,-2,-2,-2,-1,-1,-1,-1,0,0,1,1,1,1,2,2,2,2,2]
count = 0
 
que = [(Ch,Cw)]
que_warp =[(Ch,Cw)]
res_S[Ch-1][Cw-1] = 0
 
while (que or que_warp):
    l = len(que)
    while (que):
        if l > 0:
            que_warp.append(que[0])
            l -= 1
        for i in range(4):
            nx = int(que[0][0]+dx[i])
            ny = int(que[0][1]+dy[i])
            if (1<=nx<=H) and (1<=ny<=W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1]=count
                    que.append((nx,ny))
                    que_warp.append((nx,ny))
        que.pop(0)
 
    count += 1
 
    while(que_warp):
        for i in range(len(ddx)):
            nx = int(que_warp[0][0] + ddx[i])
            ny = int(que_warp[0][1] + ddy[i])
            if (1 <= nx <= H) and (1 <= ny <= W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1] = count
                    que.append((nx, ny))
        que_warp.pop(0)
 
print (res_S[Dh-1][Dw-1])

Solution (Python):
import collections

h, w = map(int, input().split(" "))
sr, sc = map(int, input().split(" "))
er, ec = map(int, input().split(" "))

board=[['' for i in range(w)] for j in range(h)]
for i in range(h):
    s=input()
    for j in range(w):
        board[i][j]= s[j]
rs,cs=collections.deque([sr-1]),collections.deque([sc-1])
magic=[[1e6 for i in range(w)] for j in range(h)]
dr=[-1,1,0,0]
dc=[0,0,-1,1]
magic[sr-1][sc-1]=0
while len(rs)>0:
    r,c=rs.popleft(),cs.popleft()
    for i in range(4):
        nr,nc= r+dr[i],c+dc[i]
        if nr < 0 or nr >= h or nc < 0 or nc >= w or board[nr][nc] == '
            continue
        if magic[nr][nc]>magic[r][c]:
            magic[nr][nc]= magic[r][c]
            rs.appendleft(nr)
            cs.appendleft(nc)
    
    for nr in range(r-2,r+3):
        for nc in range(c-2,c+3):
            if nr < 0 or nr >= h or nc < 0 or nc >= w or board[nr][nc] == '
                continue
            if magic[nr][nc] > magic[r][c]+1:
                    magic[nr][nc] = magic[r][c]+1
                    rs.append(nr)
                    cs.append(nc)
print(magic[er-1][ec-1] if magic[er-1][ec-1]<1e6 else -1)

Solution (Python):
from collections import deque
lrud = [[0, -1], [0, 1], [-1, 0], [1, 0]]
magic = [[i, j] for i in range(-2, 3) for j in range(-2, 3)]
H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Ch, Cw = Ch-1, Cw-1
Dh, Dw = map(int, input().split())
Dh, Dw = Dh-1, Dw-1
S = [list(input()) for i in range(H)]
is_visited = [[-1 for j in range(W)]for i in range(H)]

d = deque()
d.appendleft((0, (Ch, Cw)))
while d:
    cost, (x, y) = d.popleft()
    if is_visited[x][y] != -1:
        continue
    is_visited[x][y] = cost
    for dx, dy in lrud:
        nx, ny = x+dx, y+dy
        if 0 <= nx < H and 0 <= ny < W and is_visited[nx][ny] == -1 and S[nx][ny] == '.':
            d.appendleft((cost, (nx,ny)))
    for dx, dy in magic:
        nx, ny = x+dx, y+dy
        if 0 <= nx < H and 0 <= ny < W and is_visited[nx][ny] == -1 and S[nx][ny] == '.':
            d.append((cost+1, (nx,ny)))


print(is_visited[Dh][Dw])

Solution (Python):
def check(g,h,w,s):
    if (g[0]<0 or g[0]>=h) or (g[1]<0 or g[1]>=w):
        return False
    if s[g[0]][g[1]]==-1:
        return True
    else:
        return False



h,w=map(int,input().split())
c=[int(x)-1 for x in input().split()]
d=[int(x)-1 for x in input().split()]
s=[]
for j in range(h):
    l=[-1 if x=="." else -2 for x in list(input())]
    s.append(l)
s[c[0]][c[1]]=0
u=[c]
i=0
t=0
while t==0:
    for j in u:
        if j==d:
            t=1
            break
        for k in [[j[0]-1,j[1]],[j[0]+1,j[1]],[j[0],j[1]-1],[j[0],j[1]+1]]:
            if check(k,h,w,s):
                s[k[0]][k[1]]=i
                u.append(k)
    i+=1
    v=[]
    for j in u:
        if j==d:
            t=1
            break
        for k1 in range(-2,3):
            for k2 in range(-2,3):
                k=[j[0]+k1,j[1]+k2]
                if check(k,h,w,s):
                    s[k[0]][k[1]]=i
                    v.append(k)
    if v==[]:
        t=1
    u=v
print(s[d[0]][d[1]])

Solution (Python):


import sys
from collections import deque
sys.setrecursionlimit(10**7)
input=sys.stdin.readline
h,w=map(int,input().split())
c=[int(i)-1 for i in input().split()]
d=[int(i)-1 for i in input().split()]
s=[input() for i in range(h)]
inf=100000000
dp=[[-1 if s[i][j]=="
dp[c[0]][c[1]]=0
now=deque([[c[0],c[1]]])
def bfs():
    global h,w,s,dp,now
    while len(now):
        i,j=now.popleft()
        if i>0:
            if dp[i-1][j]!=-1:
                if dp[i-1][j]>dp[i][j]:
                    dp[i-1][j]=dp[i][j]
                    now.appendleft([i-1,j])
        if j>0:
            if dp[i][j-1]!=-1:
                if dp[i][j-1]>dp[i][j]:
                    dp[i][j-1]=dp[i][j]
                    now.appendleft([i,j-1])
        if i<h-1:
            if dp[i+1][j]!=-1:
                if dp[i+1][j]>dp[i][j]:
                    dp[i+1][j]=dp[i][j]
                    now.appendleft([i+1,j])
        if j<w-1:
            if dp[i][j+1]!=-1:
                if dp[i][j+1]>dp[i][j]:
                    dp[i][j+1]=dp[i][j]
                    now.appendleft([i,j+1])
        for k in range(-2,3):
            for l in range(-2,3):
                if 0<=i+k<h and 0<=j+l<w:
                    if dp[i+k][j+l]!=-1:
                        if dp[i+k][j+l]>dp[i][j]+1:
                            dp[i+k][j+l]=dp[i][j]+1
                            now.append([i+k,j+l])
bfs()
print(dp[d[0]][d[1]] if dp[d[0]][d[1]]!=inf else -1)

Solution (Python):
from collections import deque
H,W=map(int,input().split())
c=list(map(int,input().split()))
d=list(map(int,input().split()))
s=[list(input()) for _ in range(H)]
INF=10000000
dp=[[INF for _ in range(W)] for _ in range(H)]

def walk_bfs(y,x,v):
  
  dp[y][x] = v
  path = deque()
  path.append([y,x])
  ret = deque()
  while path:
    y,x = path.popleft()
    ret.append([y,x])
    for i,j in ((0,1),(0,-1),(1,0),(-1,0)):
      if not (0 <= y+i < H and 0 <= x+j < W):
        continue
      if s[y+i][x+j] == '
        dp[y+i][x+j] = -1
      elif dp[y+i][x+j] == INF:
        dp[y+i][x+j] = v
        path.append([y+i,x+j])
  return ret

def warp_bfs():
  
  deq = walk_bfs(c[0]-1,c[1]-1,0)
  while deq:
    y,x = deq.popleft()
    for yi in range(max(0,y-2),min(H,y+3)):
      for xi in range(max(0,x-2),min(W,x+3)):
        if s[yi][xi]=='
          dp[yi][xi] = -1
          continue
        if dp[yi][xi]==INF:
          deq.extend(walk_bfs(yi,xi,dp[y][x]+1))

warp_bfs()
ans = dp[d[0]-1][d[1]-1]
if 0<= ans < INF:
  print(ans)
else:
  print(-1)

Solution (Python):

from collections import deque


H, W = [int(x) for x in input().split()]
Ch, Cw = [int(x) - 1 for x in input().split()]
Dh, Dw = [int(x) - 1 for x in input().split()]

warp_list = [(-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)]

maze = []
warp_count = []
for _ in range(H):
    line = list([x for x in input()])
    maze.append(line)
    warp_count.append([-1] * W)

queue = deque()
warp_queue = deque()

queue.appendleft((Ch, Cw, 0))
warp_count[Ch][Cw] = 0

answer = -1
warp_set = set()
while queue:
    def maze_check(h, w, use_magic):
        if h < 0 or H <= h:
            return False
        if w < 0 or W <= w:
            return False
        if warp_count[h][w] == -1:
            return True
        if warp_count[h][w] <= use_magic:
            return False

    def is_wall(h, w):
        if maze[h][w] == '
            return True
        return False

    now_h, now_w, use_magic = queue.pop()

    if now_h == Dh and now_w == Dw:
        if answer == -1:
            answer = use_magic

        elif answer > use_magic:
            answer = use_magic

        continue

    
    for y, x in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
        if maze_check(now_h + y, now_w + x, use_magic):

            
            if is_wall(now_h + y, now_w + x):
                if not (now_h, now_w) in warp_set:
                    warp_queue.appendleft((now_h, now_w, use_magic))
                    warp_set.add((now_h, now_w))
            else:
                queue.appendleft((now_h + y, now_w + x, use_magic))
                warp_count[now_h + y][now_w + x] = use_magic

    if not queue:
        while warp_queue:
            now_h, now_w, use_magic = warp_queue.pop()

            for y, x in warp_list:
                warp_h = now_h + y
                warp_w = now_w + x

                if maze_check(warp_h, warp_w, use_magic+1):
                    if not is_wall(warp_h, warp_w):
                        queue.append((warp_h, warp_w, use_magic+1))
                        warp_count[warp_h][warp_w] = use_magic + 1
        warp_set = set()

print(answer)

Solution (Python):
from collections import deque

H, W = map(int, input().split())
Si, Sj = map(int, input().split())
Gi, Gj = map(int, input().split())

S = ["

INF = float("inf")
D = [[INF] * (W + 2) for _ in range(H + 2)]
D[Si][Sj] = 0
Q = deque([(0, Si, Sj)])
while Q:
    c, i, j = Q.popleft()
    if (i, j) == (Gi, Gj):
        print(D[i][j])
        quit()

    for ni, nj in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
        if 1 <= ni <= H and 1 <= nj <= W and D[ni][nj] > c and S[ni][nj] == ".":
            D[ni][nj] = c
            Q.appendleft((c, ni, nj))

    for di in range(-2, 3):
        for dj in range(-2, 3):
            ni, nj = i + di, j + dj
            if 1 <= ni <= H and 1 <= nj <= W and (di, dj) not in [(1, 0), (0, 1), (-1, 0), (0, -1), (0, 0)] and D[ni][nj] > c + 1 and S[ni][nj] == ".":
                D[ni][nj] = c + 1
                Q.append((c + 1, ni, nj))

print(-1)

Solution (Python):

 
dx = [-1,0,1,0]
dy = [0,-1,0,1]
 
def bfs(ch,cw):
    q = [[] for _ in range(1000000)]
    
    S[ch][cw] = 0
    q[S[ch][cw]].append([ch,cw])
    
    counter = 0
    
    while True:
        if not q[counter]:
          counter += 1
          if not q[counter]:
              break
        p = q[counter].pop()
        
        if p[0]==dh and p[1]==dw:
            break
        
        for i in range(4):
            next_p = [p[0]+dx[i],p[1]+dy[i]]
            if next_p[0]<0 or next_p[1]<0 or next_p[0]>=h or next_p[1]>=w:
                continue
            if S[next_p[0]][next_p[1]] > S[p[0]][p[1]]:
                S[next_p[0]][next_p[1]] = S[p[0]][p[1]]
                q[counter].append(next_p)
                
                
        for i in range(-2,3):
            for j in range(-2,3):
                if (i == 0 and j == 0) or (i==-1 and j==0)or(i==1 and j==0)or(i==0 and j==-1)or (i==0 and j==1):
                    continue
                next_p = [p[0]+i,p[1]+j]
                if next_p[0]<0 or next_p[1]<0 or next_p[0]>=h or next_p[1]>=w:
                    continue
                if S[next_p[0]][next_p[1]] > S[p[0]][p[1]]+1:
                    S[next_p[0]][next_p[1]] = S[p[0]][p[1]]+1
                    q[counter+1].append(next_p)
                    
            
    return 
        
h,w = map(int,input().split())
ch,cw = map(int,input().split())
ch -= 1
cw -= 1
dh,dw = map(int,input().split())
dh -= 1
dw -= 1
S = [list(input()) for _ in range(h)]
 
for i in range(h):
    for j in range(w):
        if S[i][j] == '.':
            S[i][j] = float('inf')
        else:
            S[i][j] = -1
 
 
bfs(ch,cw)
if S[dh][dw] != float('inf'):
    print(S[dh][dw])
else:
    print(-1)

Solution (Python):
import sys

def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
from collections import deque

def main():
    h, w = MII()
    ch, cw = MII()
    dh, dw = MII()
    maze = [IS() for _ in range(h)]
    check = [[-1]*w for i in range(h)]
    dq = deque([(ch-1, cw-1)])
    check[ch-1][cw-1] = 0
    count = 0

    inMaze = lambda x,y: 0 <= y < h and 0 <= x < w
    isWall = lambda x,y: maze[y][x] == '
    isChecked = lambda x,y: check[y][x] != -1

    while True:
        tmp = []
        while dq:
            y, x = dq.popleft()
            tmp.append((y, x))
            for dy, dx in ((0,1), (0,-1), (1,0), (-1,0)):
                ny = y+dy
                nx = x+dx
                if not inMaze(nx, ny):
                    continue
                if isWall(nx, ny):
                    continue
                if isChecked(nx, ny):
                    continue
                check[ny][nx] = count
                dq.appendleft((ny, nx))

        count += 1
        for y, x in tmp:
            for i in range(-2,3):
                for j in range(-2,3):
                    ny = y+i
                    nx = x+j
                    if not inMaze(nx, ny):
                        continue
                    if isWall(nx, ny):
                        continue
                    if isChecked(nx, ny):
                        continue
                    check[ny][nx] = count
                    dq.append((ny, nx))
        if not dq:
            break

    print(check[dh-1][dw-1])

if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007

dxdy4 = ((-1, 0), (0, -1), (0, 1), (1, 0))


def main():
    H, W = map(int, readline().split())
    Ch, Cw = map(int, readline().split())
    Dh, Dw = map(int, readline().split())
    S = [readline().strip() for _ in range(H)]

    Ch -= 1
    Cw -= 1
    Dh -= 1
    Dw -= 1

    dist = [[INF] * W for _ in range(H)]
    dist[Ch][Cw] = 0
    seen = [[False] * W for _ in range(H)]
    queue = deque([(Ch, Cw)])
    while queue:
        x, y = queue.popleft()
        seen[x][y] = True
        for dx, dy in dxdy4:
            nx, ny = x + dx, y + dy
            if (
                0 <= nx < H
                and 0 <= ny < W
                and not seen[nx][ny]
                and (dist[nx][ny] == -1 or dist[nx][ny] > dist[x][y])
                and S[nx][ny] == '.'
            ):
                dist[nx][ny] = dist[x][y]
                queue.appendleft((nx, ny))
        for dx in range(-2, 3):
            for dy in range(-2, 3):
                nx, ny = x + dx, y + dy
                if (
                    0 <= nx < H
                    and 0 <= ny < W
                    and not seen[nx][ny]
                    and dist[nx][ny] > dist[x][y] + 1
                    and S[nx][ny] == '.'
                ):
                    dist[nx][ny] = dist[x][y] + 1
                    queue.append((nx, ny))

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

    return


if __name__ == '__main__':
    main()