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):
from collections import deque
import sys
input = sys.stdin.readline

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 = [input().rstrip() for _ in range(H)]
visited = [[False] * W for _ in range(H)]
dq = deque([(0, Ch, Cw)])
while dq:
    d, i, j = dq.popleft()
    if (i, j) == (Dh, Dw):
        print(d)
        exit()
    if visited[i][j]:
        continue
    visited[i][j] = True
    for di, dj in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        ni, nj = i + di, j + dj
        if 0 <= ni < H and 0 <= nj < W and S[ni][nj] == '.':
            dq.appendleft((d, ni, nj))
    for di in range(-2, 3):
        for dj in range(-2, 3):
            if di == dj == 0:
                continue
            ni, nj = i + di, j + dj
            if 0 <= ni < H and 0 <= nj < W and S[ni][nj] == '.' and not visited[ni][nj]:
                dq.append((d + 1, ni, nj))
print(-1)

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()
        if seen[x][y]:
            continue
        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()

Solution (Python):
from collections import deque

Y, X = map(int,input().split())
sy, sx = map(int, input().split())
gy, gx = map(int, input().split())
s = [["
for y in range(Y):
    s[y+2] = *list("
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [[-1,0],[1,0],[0,0],[0,-1],[0,1]]
dr2s = [[-2,-2],[-2,-1],[-2,0],[-2,1],[-2,2],
        [2,-2],[2,-1],[2,0],[2,1],[2,2],
        [-1,-2],[0,-2],[1,-2],
        [-1,2],[0,2],[1,2],
        [-1,-1],[-1,1],[1,-1],[1,1]
       ]

q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+2][x2+2] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost
            q.appendleft((y2,x2))
    for dy, dx in dr2s:
        x2 = x+dx
        y2 = y+dy
        if s[y2+2][x2+2] == "." and c[y2][x2] > cost+1:
            c[y2][x2] = cost+1
            q.append((y2,x2))
    
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    print(c[gy-1][gx-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())

L=[]
for h in range(H):
    s=list(input())
    L.append(s)

def isOK(h,w):
    if 0<=h<H and 0<=w<W:
        if L[h][w]==".":
            return True
    return False

que=deque([(ch-1,cw-1,0)])
DX=[0,1,0,-1]
DY=[1,0,-1,0]

cost=[[-1]*W for _ in range(H)]
cost[ch-1][cw-1]=0
count=0
while que:
    lis=[]
    while que:
        
        t=que.popleft()
        x,y,now=t
        lis.append((x,y))
        for i in range(4):
            dx=DX[i]
            dy=DY[i]
            nx=x+dx
            ny=y+dy
            if isOK(nx,ny):
                if cost[nx][ny]==-1:
                    cost[nx][ny]=now
                    que.append((nx,ny,now))
                    lis.append((nx,ny))
    for t in lis:
        x,y=t
        for dx in range(-2,3):
            for dy in range(-2,3):
                if abs(dx)+abs(dy)<=1:
                    continue
                nx=x+dx
                ny=y+dy
                if isOK(nx,ny):
                    if cost[nx][ny]==-1 or cost[nx][ny]>count+1:
                        cost[nx][ny]=count+1
                        que.append((nx,ny,count+1))
    count+=1


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

Solution (Python):

import sys
from collections import defaultdict, deque

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

visit=defaultdict(lambda: 0) 
d=defaultdict(lambda: float("inf")) 

q=deque()
q.append((CH,CW))
d[(CH,CW)]=0

while q:
    fro_h, fro_w=q.popleft()
    if fro_h==DH and fro_w==DW:
        print d[(fro_h, fro_w)]
        quit()
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]<d[(to_h, to_w)]:
            d[(to_h, to_w)]=d[(fro_h, fro_w)]
            q.appendleft((to_h, to_w))

    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]+1<d[(to_h, to_w)]:
            d[(to_h, to_w)]=d[(fro_h, fro_w)]+1
            q.append((to_h, to_w))

print -1

Solution (Python):

import sys
from collections import defaultdict, deque

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

visit=defaultdict(lambda: 0) 
d=defaultdict(lambda: float("inf")) 

q=deque()
q.append((CH,CW))
d[(CH,CW)]=0

while q:
    fro_h, fro_w=q.popleft()
    if fro_h==DH and fro_w==DW:
        print d[(fro_h, fro_w)]
        quit()
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]<d[(to_h, to_w)] and visit[(to_h, to_w)]==0:
            visit[(to_h, to_w)]==1
            d[(to_h, to_w)]=d[(fro_h, fro_w)]
            q.appendleft((to_h, to_w))

    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]+1<d[(to_h, to_w)] and visit[(to_h, to_w)]==0:
            visit[(to_h, to_w)]==1
            d[(to_h, to_w)]=d[(fro_h, fro_w)]+1
            q.append((to_h, to_w))

print -1

Solution (Python):
from collections import deque

def idx(h,w):
    return h*W + w

def main():
    adj=[(-1,0), (0,1), (1,0), (0,-1)]
    graph=[set() for _ in range(N)]
    for h in range(H):
        for w in range(W):
            idx_from=idx(h,w)
            if Ss[h][w]=='
                continue
            for dh in range(-2,3):
                for dw in range(-2,3):
                    if dh==0 and dw==0:
                        continue
                    h_dst=h+dh
                    w_dst=w+dw
                    
                    if (0<=h_dst<H) and (0<=w_dst<W) and (Ss[h_dst][w_dst]=='.'):
                        idx_to=idx(h_dst,w_dst)
                        if (dh,dw) in adj:
                            graph[idx_from].add((idx_to,0))
                            
                        else:
                            graph[idx_from].add((idx_to,1))
                            
    s=idx(Ch,Cw)
    dist=[10**9]*N
    dist[s]=0
    que=deque()
    que.append(s)

    while len(que)>0:
        i = que.popleft() 
        for j,c in graph[i]:
            d = dist[i] + c
            if d < dist[j]:
                dist[j] = d
                if c == 1:
                    que.append(j) 
                else:
                    que.appendleft(j) 
    
    ans = dist[idx(Dh,Dw)]
    print(-1 if ans == 10**9 else ans)

H,W=map(int,input().split())
N=H*W
Ch,Cw=[int(e)-1 for e in input().split()]
Dh,Dw=[int(e)-1 for e in input().split()]
Ss=[]
for _ in range(H):
    
    Ss.append(input())
main()

Solution (Python):
import collections
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
s = [input() for _ in range(h)]

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

d = collections.deque()
d.append((ch, cw))
visit = set()
x = ch
y = cw
cost = [[-1]*w for _ in range(h)]
cost[ch][cw] = 0

while len(d) > 0:
    x, y = d.popleft()
    if (x, y) not in visit:
        visit.add((x, y))
    else:
        continue
    for i in range(5):
        for j in range(5):
            x_n = x+i-2
            y_n = y+j-2
            if x_n >= 0 and x_n < h and y_n >= 0 and y_n < w:
                if s[x_n][y_n] == '.' and (x_n, y_n) not in visit:
                    if pow(i-2, 2)+pow(j-2, 2) == 1:
                            d.appendleft((x_n, y_n))
                            cost[x_n][y_n] = cost[x][y]
                    else:
                        d.append((x_n, y_n))
                        if cost[x_n][y_n] == -1:
                            cost[x_n][y_n] = cost[x][y]+1

print(cost[dh][dw])

Solution (Python):
from collections import deque







def main():
    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 = []
    S.append(["
    S.append(["
    for i in range(H):
        S.append(["
    S.append(["
    S.append(["
    dist = [[10 ** 18] * (4 + W) for _ in range(H + 4)]
    

    def bfs(i, j):
        q = deque()
        q.append((i, j))
        dist[i][j] = 0
        while q:
            a, b = q.popleft()
            for x in range(-2, 3):
                for y in range(-2, 3):
                    if S[a + x][b + y] == ".":
                        warp = abs(x) + abs(y) != 1
                        d = dist[a][b] + int(warp)
                        if d < dist[a + x][b + y]:
                            dist[a + x][b + y] = d
                            if warp:
                                q.append((a + x, b + y))
                            else:
                                q.appendleft((a + x, b + y))
                            

    bfs(Ch + 2, Cw + 2)
    if dist[Dh + 2][Dw + 2] == 10 ** 18:
        print(-1)
    else:
        print(dist[Dh + 2][Dw + 2])


if __name__ == "__main__":
    main()

Solution (Python):
import collections, itertools

h, w = map(int, input().split())
ch, cw = tuple(int(s) - 1 for s in input().split())
dh, dw = tuple(int(s) - 1 for s in input().split())
s = [input() for _ in range(h)]

q = collections.deque()
q.append((ch, cw, 0))
score = [[float('inf')] * w for _ in range(h)]
score[ch][cw] = 0
while q:
    x, y, p = q.popleft()

    for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and p < score[nx][ny]:
            score[nx][ny] = p
            q.appendleft((nx, ny, p))
    
    for dx, dy in itertools.product(range(-2, 3), repeat=2):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and p + 1 < score[nx][ny]:
            score[nx][ny] = p + 1
            q.append((nx, ny, p + 1))

if score[dh][dw] == float('inf'):
    print(-1)
else:
    print(score[dh][dw])

Solution (Python):

import sys
from collections import deque
def main():
    movey = (0, -1, 0, 1)
    movex = (1, 0, -1, 0)
    warpy = (-2, -2, -2, -2, -2, -1, -1, -1, -1,  0, 0,  1,  1, 1, 1, 2, 2, 2, 2, 2)
    warpx = (-2, -1,  0,  1,  2, -2, -1,  1,  2, -2, 2, -2, -1, 1, 2, -2, -1, 0, 1, 2)

    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
    dummy = tuple(['
    maze = {e: [] for e in range(h + 4)}
    maze[0] = dummy
    maze[1] = dummy
    for i in range(h):
        row = ['
        maze[i+2] = row
    maze[h+2] = dummy
    maze[h+3] = dummy
    maze[ch][cw] = 0
    maze[dh][dw] = 'g'

    nodes = deque()
    nodes.append((ch, cw))
    res = []
    while nodes:
        (n_y, n_x) = nodes.popleft()
        cur_masu = maze[n_y][n_x]
        flag = False
        for j1 in range(4):
            ny = n_y + movey[j1]
            nx = n_x + movex[j1]
            next_masu = maze[ny][nx]
            if next_masu == 'g':
                res.append(cur_masu)
            elif next_masu == '.':
                maze[ny][nx] = cur_masu
                nodes.appendleft((ny, nx))
            elif next_masu == '
                flag = True
            elif next_masu > cur_masu:
                maze[ny][nx] = cur_masu
                nodes.appendleft((ny, nx))
        if flag:
            for j1 in range(20):
                ny = n_y + warpy[j1]
                nx = n_x + warpx[j1]
                next_masu = maze[ny][nx]
                if next_masu == 'g':
                    res.append(cur_masu+1)
                elif next_masu == '.':
                    maze[ny][nx] = cur_masu + 1
                    nodes.append((ny, nx))
                elif next_masu == '
                    pass
                elif next_masu > cur_masu + 1:
                    maze[ny][nx] = cur_masu + 1
                    nodes.append((ny, nx))

    if res:
        print(min(res))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Solution (Python):

from collections import deque

H, W = map(int, input().split())
C = tuple(map(int, input().split())) 
D = tuple(map(int, input().split())) 
D_y = D[0] -1 
D_x = D[1] -1 
S = [list(input()) for _ in range(H)]
visited = [[-1] * W for _ in range(H)]
visited[C[0]-1][C[1]-1] = 0 
moves = [(1, 0), (0, 1), (-1, 0), (0, -1)] 
main_q = deque()
magic_q = deque() 
main_q.append((C[0]-1, C[1]-1))

while main_q:
    y, x = main_q.popleft()
    magic_q.append((y, x))
    for move in moves:
        dy, dx = move
        moved_y = y + dy
        moved_x = x + dx

        if moved_y < 0 or H -1 < moved_y or moved_x < 0 or W -1 < moved_x:
            continue
        if S[moved_y][moved_x] == '
            continue
        if S[moved_y][moved_x] == '.' and visited[moved_y][moved_x] == -1:
            main_q.append((moved_y, moved_x))
            visited[moved_y][moved_x] = visited[y][x]
    
    if not main_q: 
        while magic_q:
            y, x = magic_q.popleft()
            for dy in range(-2, 3):
                for dx in range(-2, 3):
                    moved_y = y + dy
                    moved_x = x + dx

                    if moved_y < 0 or H -1 < moved_y or moved_x < 0 or W -1 < moved_x:
                        continue
                    if S[moved_y][moved_x] == '
                        continue
                    if S[moved_y][moved_x] == '.' and visited[moved_y][moved_x] == -1:
                        main_q.append((moved_y, moved_x))
                        visited[moved_y][moved_x] = visited[y][x] + 1

answer = visited[D_y][D_x]
print(answer)

Solution (Python):

import sys
from collections import defaultdict, deque

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

visit=defaultdict(lambda: 0) 
d=defaultdict(lambda: float("inf")) 

q=deque()
q.append((CH,CW))
d[(CH,CW)]=0

while q:
    fro_h, fro_w=q.popleft()
    if visit[(fro_h, fro_w)]==1: continue
    visit[(fro_h, fro_w)]=1
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]<d[(to_h, to_w)] and visit[(to_h, to_w)]==0:
            d[(to_h, to_w)]=d[(fro_h, fro_w)]
            q.appendleft((to_h, to_w))

    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]+1<d[(to_h, to_w)] and visit[(to_h, to_w)]==0:
            d[(to_h, to_w)]=d[(fro_h, fro_w)]+1
            q.append((to_h, to_w))

if d[(DH,DW)]==float("inf"):
    print -1
else:
    print d[(DH,DW)]

Solution (Python):
from collections import deque

H, W = map(int, input().split())
sy, sx = map(int, input().split())
gy, gx = map(int, input().split())
map_list = []
for i in range(H):
    str_input = input()
    map_list.append(list(str_input))

walk = [[1,0], [-1,0], [0,1], [0,-1]] 
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]]

dist = [[10**12 for _ in range(W)] for i in range(H)] 

d = deque()
d.append([sy-1, sx-1])
dist[sy-1][sx-1] = 0


while d:
    y,x = d.popleft()
    for dy,dx in walk:
        new_x = x + dx
        new_y = y + dy
        if 0 <= new_y < H and 0 <= new_x < W and map_list[new_y][new_x] == '.' and dist[new_y][new_x] > dist[y][x]:
            dist[new_y][new_x] = dist[y][x]
            d.appendleft([new_y, new_x]) 
    for dy, dx in warp:
        new_x = x + dx
        new_y = y + dy
        if 0 <= new_y < H and 0 <= new_x < W and map_list[new_y][new_x] == '.' and dist[new_y][new_x] > dist[y][x] + 1:
            dist[new_y][new_x] = dist[y][x] + 1
            d.append([new_y, new_x]) 


ans = dist[gy-1][gx-1]
if ans == 10**12:
    ans = -1
print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

INF = 10**18
eps = 10**-7

from collections import deque
import itertools

h,w = map(int,readline().split())
cx,cy = map(int,readline().split())
gx,gy = map(int,readline().split())
cx -= 1
cy -= 1
grid = [readline().rstrip() for i in range(h)]

dist = [[INF]*w for i in range(h)]
dist[cx][cy] = 0

l2 = list(itertools.product([-2,-1,0,1,2],repeat = 2))
l1 = [(-1,0),(1,0),(0,-1),(0,1)]
q1 = deque([(cx,cy)])
q2 = deque([(cx,cy)])

while q1 or q2:
    if q1:
        x,y = q1.popleft()
        for dy,dx in l1:
            ny,nx = y+dy, x+dx
            if not (0 <= ny < w and 0 <= nx < h):
                continue
            if grid[nx][ny] == '
                continue
            if dist[nx][ny] > dist[x][y]:
                dist[nx][ny] = dist[x][y]
                q1.append((nx,ny))
                q2.append((nx,ny))
    else:
        x,y = q2.popleft()
        for dy,dx in l2:
            ny,nx = y+dy, x+dx
            if not (0 <= ny < w and 0 <= nx < h):
                continue
            if grid[nx][ny] == '
                continue
            if dist[nx][ny] > dist[x][y]+1:
                dist[nx][ny] = dist[x][y]+1
                q1.append((nx,ny))
                q2.append((nx,ny))

print(dist[gx-1][gy-1] if dist[gx-1][gy-1] != INF else -1)

Solution (Python):
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7

INF = 10**18
eps = 10**-7

from collections import deque
import itertools

h,w = map(int,readline().split())
cx,cy = map(int,readline().split())
gx,gy = map(int,readline().split())
cx -= 1
cy -= 1
grid = [readline().rstrip() for i in range(h)]

dist = [[INF]*w for i in range(h)]
dist[cx][cy] = 0

l2 = list(itertools.product([-2,-1,0,1,2],repeat = 2))
l1 = [(-1,0),(1,0),(0,-1),(0,1)]
q1 = deque([(cx,cy)])

while q1:
    if q1:
        x,y = q1.popleft()
        for dy,dx in l1:
            ny,nx = y+dy, x+dx
            if not (0 <= ny < w and 0 <= nx < h):
                continue
            if grid[nx][ny] == '
                continue
            if dist[nx][ny] > dist[x][y]:
                dist[nx][ny] = dist[x][y]
                q1.appendleft((nx,ny))
        for dy,dx in l2:
            ny,nx = y+dy, x+dx
            if not (0 <= ny < w and 0 <= nx < h):
                continue
            if grid[nx][ny] == '
                continue
            if dist[nx][ny] > dist[x][y]+1:
                dist[nx][ny] = dist[x][y]+1
                q1.append((nx,ny))

print(dist[gx-1][gy-1] if dist[gx-1][gy-1] != INF else -1)

Solution (Python):


import sys
input=sys.stdin.buffer.readline
inputs=sys.stdin.buffer.readlines

h,w=map(int,input().split())
nx,ny=map(int,input().split())
gx,gy=map(int,input().split())
maze=inputs()

nx-=1;ny-=1;gx-=1;gy-=1
from collections import deque

dq=deque([(nx,ny)])
dq2=deque([])

T=[[float('inf')]*w for  a in range(h)]

T[nx][ny]=0

moves=((1,0),(-1,0),(0,1),(0,-1))
from itertools import product as pr

Mmoves=tuple(i for i in pr((-2,-1,0,1,2),repeat=2)if i!=(0,0) )

while dq:
    
    while dq:
        x,y=dq.popleft()
        for i,j in moves:
            nex,ney=x+i,y+j
            
            if not(0<=nex<h and 0<=ney<w) or maze[nex][ney]==35:continue
            if T[x][y]<T[nex][ney]:
                
                T[nex][ney]=T[x][y]
                dq.append((nex,ney))
        for i,j in Mmoves:
            nex,ney=x+i,y+j
            if not(0<=nex<h and 0<=ney<w) or maze[nex][ney]==35:continue
            if T[x][y]+1<T[nex][ney]:
                T[nex][ney]=T[x][y]+1
                dq2.append((nex,ney))
    
    dq,dq2=dq2,dq
if T[gx][gy]==float('inf'):print(-1)
else:print(T[gx][gy])

Solution (Python):
from collections import deque
def main():
    H, W = map(int, input().split())
    sh,sw = map(int, input().split())
    gh,gw = map(int, input().split())
    gh,gw = gh-1,gw-1
    field = [list(input()) for _ in range(H)]
    q = deque()
    q.append((0, sh-1, sw-1))
    INF = 10 ** 30
    dist = [[INF] * W for _ in range(H)]
    dist[sh-1][sw-1] = 0
    while q:
        cnt, h, w = deque.popleft(q)
        if dist[h][w] < cnt: continue
        if h == gh and w == gw: return cnt
        for i in range(-2, 3):
            for j in range(-2, 3):
                nh = h+i
                nw = w+j
                if nh < 0 or nw < 0: continue
                if nh >= H or nw >= W: continue
                if field[nh][nw]  == "
                if (i, j) in ((1,0),(0,1),(-1,0),(0,-1)):
                    if dist[nh][nw] <= cnt: continue
                    dist[nh][nw] = cnt
                    deque.appendleft(q, (cnt, nh, nw))
                else:
                    if dist[nh][nw] <= cnt+1: continue
                    dist[nh][nw] = cnt+1
                    deque.append(q, (cnt+1, nh, nw))
    return -1

print(main())

Solution (Python):
from collections import deque
from itertools import product
h, w = map(int, input().split())
si, sj = map(lambda x: int(x)-1, input().split())
gi, gj = map(lambda x: int(x)-1, input().split())
fld = ''.join([input()for _ in range(h)])
INF = 10**18


def to_v(i, j):
    return i*w+j


n = h*w
start = to_v(si, sj)
goal = to_v(gi, gj)


def generate_v2(v):
    i, j = divmod(v, w)
    it = [-2, -1, 0, 1, 2]
    for di, dj in product(it, repeat=2):
        x, y = i+di, j+dj
        if x < 0 or h <= x or y < 0 or w <= y:
            continue
        if (di, dj) in [(-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)]:
            d = 0
        else:
            d = 1
        yield d, x*w+y


def bfs(init_v):
    next_v = deque([init_v])
    INF = 10**18
    dist = [INF]*n
    dist[init_v] = 0
    visited = [0]*n
    while next_v:
        v = next_v.popleft()
        if visited[v]:
            continue
        visited[v] = 1
        for d, v2 in generate_v2(v):
            if fld[v2] == '
                continue
            if dist[v2] <= dist[v]+d:
                continue
            dist[v2] = dist[v]+d
            if d:
                next_v.append(v2)
            else:
                next_v.appendleft(v2)
    return dist


ans = bfs(start)[goal]
print(-1 if ans == INF else ans)

Solution (Python):





from collections import deque




def solve(H, W, C, D, Ss):
    cost_map = [[-1] * (W + 4) for _ in range(H + 4)]
    Ss = ['
    C = [c + 1 for c in C]
    D = [d + 1 for d in D]
    cost = 0
    ans = -1
    dq = deque()
    dq.append(C)
    while dq:
        next_dq = deque()
        flg = False
        while dq:
            h, w = dq.popleft()
            if h == D[0] and w == D[1]:
                ans = cost
                flg = True
                break
            if cost_map[h][w] >= 0:
                continue
            cost_map[h][w] = cost
            for i in range(h - 2, h + 2 + 1):
                for j in range(w - 2, w + 2 + 1):
                    if Ss[i][j] == '
                        continue
                    if cost_map[i][j] >= 0:
                        continue
                    if abs(h - i) + abs(w - j) == 1:
                        dq.append([i, j])
                    else:
                        next_dq.append([i, j])
        if flg:
            break
        dq = next_dq
        cost += 1
    print(ans)


if __name__ == '__main__':
    
    
    H, W = map(int, input().split())
    C = [int(i) for i in input().split()]
    D = [int(i) for i in input().split()]
    Ss = [input() for _ in range(H)]
    
    solve(H, W, C, D, Ss)

Solution (Python):
from collections import deque
h, w = map(int, input().split())
sy, sx = list(map(int, input().split()))
sy -= 1
sx -= 1
gy, gx = list(map(int, input().split()))
gy -= 1
gx -= 1
s = [input() for _ in range(h)]
inf = float("inf")
meiro = [[inf]*w for _ in range(h)]
d = deque()
d.append([sy, sx])
meiro[sy][sx] = 0
move1 = [[1, 0], [0, 1], [-1, 0], [0, -1]]
while d:
    py, px = d.popleft()
    
    for dy, dx in move1:
        if 0 <= px+dx < w and 0 <= py+dy < h:
            childy = py + dy
            childx = px + dx
            if s[childy][childx] == "." and meiro[childy][childx] > meiro[py][px]:
                meiro[childy][childx] = meiro[py][px]
                d.appendleft([childy, childx])
                

    
    for dy in range(-2, 3):
        for dx in range(-2, 3):
            if 0 <= px+dx < w and 0 <= py+dy < h:
                warpx = px + dx
                warpy = py + dy
                if s[warpy][warpx] == "." and meiro[warpy][warpx] == inf:
                    meiro[warpy][warpx] = meiro[py][px] + 1
                    d.append([warpy, warpx])


ans = meiro[gy][gx] if meiro[gy][gx] != inf else -1
print(ans)

Solution (Python):
from collections import deque
from itertools import product
h, w = map(int, input().split())
si, sj = map(lambda x: int(x)-1, input().split())
gi, gj = map(lambda x: int(x)-1, input().split())
fld = ''.join([input()for _ in range(h)])
INF = 10**18


def to_v(i, j):
    return i*w+j


n = h*w
start = to_v(si, sj)
goal = to_v(gi, gj)


def generate_v2(v):
    i, j = divmod(v, w)
    it = [-2, -1, 0, 1, 2]
    for di, dj in product(it, repeat=2):
        x, y = i+di, j+dj
        if x < 0 or h <= x or y < 0 or w <= y:
            continue
        if (di, dj) in [(-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)]:
            d = 0
        else:
            d = 1
        yield d, x*w+y


def bfs(init_v):
    next_v = deque([init_v])
    INF = 10**18
    dist = [INF]*n
    dist[init_v] = 0
    while next_v:
        v = next_v.popleft()
        for d, v2 in generate_v2(v):
            if fld[v2] == '
                continue
            if dist[v2] <= dist[v]+d:
                continue
            dist[v2] = dist[v]+d
            if d:
                next_v.append(v2)
            else:
                next_v.appendleft(v2)
    return dist


ans = bfs(start)[goal]
print(-1 if ans == INF else ans)

Solution (Python):

import sys
from collections import defaultdict, deque

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

d=defaultdict(lambda: float("inf")) 

q=deque()
q.append((0,CH,CW))
d[(CH,CW)]=0

while q:
    kyori, fro_h, fro_w=q.popleft()
    if d[(fro_h, fro_w)]<kyori: continue
    
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]==".":
            if kyori < d[(to_h, to_w)]:
                d[(to_h, to_w)]=kyori
                q.appendleft((kyori, to_h, to_w))
    
    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]==".":
            if kyori+1 < d[(to_h, to_w)]:
                d[(to_h, to_w)]=kyori+1
                q.append((kyori+1, to_h, to_w))

if d[(DH,DW)]==float("inf"):
    print -1
else:
    print d[(DH,DW)]