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
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def main():
    H, W = NMI()
    C = NLI()
    D = NLI()
    C = [x-1 for x in C]
    D = [x-1 for x in D]
    grid = [SI() for _ in range(H)]

    que = deque()
    cost = [[10**10]*W for _ in range(H)]
    cost[C[0]][C[1]] = 0
    que.append(C)
    while que:
        now = que.popleft()
        now_cost = cost[now[0]][now[1]]

        for i in range(-2, 3):
            if now[0] + i < 0 or now[0] + i >= H:
                continue
            for j in range(-2, 3):
                if now[1]+j < 0 or now[1]+j >= W:
                    continue
                if i == j == 0:
                    continue
                goto = [now[0]+i, now[1]+j]
                goto_cost = cost[goto[0]][goto[1]]
                if grid[goto[0]][goto[1]] == "
                    continue

                dist = abs(goto[0]-now[0]) + abs(goto[1]-now[1])
                if dist == 1:
                    if now_cost < goto_cost:
                        cost[goto[0]][goto[1]] = now_cost
                        que.appendleft(goto)
                else:
                    if now_cost + 1 < goto_cost:
                        cost[goto[0]][goto[1]] = now_cost + 1
                        que.append(goto)

    ans = cost[D[0]][D[1]]
    print(ans if ans < 10**10 else -1)


if __name__ == "__main__":
    main()

Solution (Python):

from collections import deque
def resolve():
    drc4 = [(0, 1), (0, -1), (-1, 0), (1, 0)]
    warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + drc4]

    H, W = map(int, input().split())
    sy, sx = map(lambda x: int(x) - 1, input().split())
    gy, gx = map(lambda x: int(x) - 1, input().split())
    G = [input() for _ in range(H)]

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

    q = deque()
    q.append((sy, sx))
    dist[sy][sx] = 0
    cnt = 0
    while True:
        next_warp = []
        while q:
            sy, sx = q.popleft()
            next_warp.append((sy, sx))
            for dy, dx in drc4:
                ny = dy + sy
                nx = dx + sx
                if 0 <= ny < H and 0 <= nx < W and G[ny][nx] == "." and dist[ny][nx] == INF:
                    dist[ny][nx] = cnt
                    q.append((ny, nx))

        for sy, sx in next_warp:
            for dy8, dx8 in warp:
                ny8 = dy8 + sy
                nx8 = dx8 + sx
                if 0 <= ny8 < H and 0 <= nx8 < W and G[ny8][nx8] == "." and dist[ny8][nx8] == INF:
                    dist[ny8][nx8] = cnt + 1
                    q.append((ny8, nx8))

        if not q or dist[gy][gx] != INF:
            break
        cnt += 1

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


if __name__ == "__main__":
    resolve()

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


def main():
    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
    
    
    s = ["
    s.append("
    for i in range(h):
        s.append("
    s.append("
    s.append("
    
    
    ans = [[-1]*(w+4) for _ in range(h+4)]
    for i in range(h+4):
        for j in range(w+4):
            if s[i][j] == "
                ans[i][j] = -2
    ans[ch][cw] = 0
    
    move = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    not_yet = deque([(ch, cw)])
    one_time = deque([])
    
    while len(not_yet) > 0:
        x, y = not_yet.popleft()
        one_time.append((x, y))
        for (p, q) in move:
            if ans[x+p][y+q] == -1:
                not_yet.append((x+p, y+q))
                ans[x+p][y+q] = ans[x][y]
                
        if len(not_yet) == 0:
            while len(one_time) > 0:
                x2, y2 = one_time.popleft()
                for i in range(x2-2, x2+3):
                    for j in range(y2-2, y2+3):
                        if ans[i][j] == -1:
                            ans[i][j] = ans[x2][y2]+1
                            not_yet.append((i, j))
          
    print(ans[dh][dw])
    
    
    
if __name__ == "__main__":
    main()

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


H,W = map(int, input().split())
c1,c2= map(int, input().split())
d1,d2= map(int, input().split())
A=[list(input()) for i in range(H)]
edges = [[] for i in range(H * W)]

for i in range(H):
    for j in range(W):
        for di in range(-2,3):
            for dj in range(-2, 3):
                ni, nj = i + di, j + dj
                if 0 <= ni < H and 0 <= nj < W and A[i][j]!='
                    if di==0 and dj==0:
                        continue
                    elif (di==0 and dj==1) or (di==1 and dj==0) or (di==-1 and dj==0) or (di==0 and dj==-1):
                        edges[i * W + j].append((ni * W + nj,0))
                    else:
                        edges[i * W + j].append((ni * W + nj,1))

s=(c1-1)*W+c2-1
g=(d1-1)*W+d2-1
dist = [10**9]*(H*W)
dist[s] = 0
que = deque()
que.append(s)

while len(que) > 0:
    i = que.popleft()
    for j, c in edges[i]:
        d = dist[i] + c
        if d < dist[j]:
            dist[j] = d
            if c == 1:
                que.append(j)
            else:
                que.appendleft(j)


ans=dist[g]
if ans==pow(10,9):
    print(-1)
else:
    print(ans)

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


def main():
    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
    
    
    s = ["
    s.append("
    for i in range(h):
        s.append("
    s.append("
    s.append("
    
    
    ans = [[-1]*(w+4) for _ in range(h+4)]
    for i in range(h+4):
        for j in range(w+4):
            if s[i][j] == "
                ans[i][j] = -2
    ans[ch][cw] = 0
    
    move = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    not_yet = deque([(ch, cw)])
    one_time = deque([])
    
    while len(not_yet) > 0:
        x, y = not_yet.popleft()
        one_time.append((x, y))
        for (p, q) in move:
            if ans[x+p][y+q] == -1:
                not_yet.append((x+p, y+q))
                ans[x+p][y+q] = ans[x][y]
                
        if len(not_yet) == 0:
            while len(one_time) > 0:
                x2, y2 = one_time.popleft()
                for i in range(x2-2, x2+3):
                    for j in range(y2-2, y2+3):
                        if ans[i][j] == -1:
                            ans[i][j] = ans[x2][y2]+1
                            not_yet.append((i, j))
                            
                      
    print(ans[dh][dw])
    
    
    
if __name__ == "__main__":
    main()

Solution (Python):

from collections import deque

H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh_, dw_ = map(int, input().split())
fs = [input() for i in range(H)]

INF = float("inf")
N = 10**4
dps = [[INF]*W for i in range(H)]
dps[ch-1][cw-1] = 0
q = deque([])
q.append((0, (ch-1)*N+(cw-1)))
while q:
    cnt, n  = q.popleft()
    h,w = divmod(n, N)
    if cnt > dps[h][w]:continue
    dps[h][w] = cnt
    
    for dh in range(-2,3):
        for dw in range(-2,3):            
            hn = h + dh
            wn = w + dw
            if not 0 <= wn < W: continue
            if not 0 <= hn < H: continue
            if fs[hn][wn] == "
            if dps[hn][wn] < INF:continue
            if abs(dh) + abs(dw) <= 1:
                q.appendleft((cnt, hn*N+wn))
            else:
                q.append((cnt+1, hn*N+wn))


ans = dps[dh_-1][dw_-1]
print(ans if ans != INF else -1)

Solution (Python):
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
grid=[]
for i in range(h):
    s=list(input())
    news=[-1 if x=='
    grid.append(news)
dif=[(1,0),(-1,0),(0,1),(0,-1)]
from collections import deque
col=0
for i in range(h):
    for j in range(w):
        if grid[i][j]==0:
            col+=1
            stack=deque([(i,j)])
            grid[i][j]=col
            while stack:
                nowi,nowj=stack.popleft()
                for di,dj in dif:
                    if 0<=nowi+di<h and 0<=nowj+dj<w and grid[nowi+di][nowj+dj]==0:
                        stack.append((nowi+di,nowj+dj))
                        grid[nowi+di][nowj+dj]=col
start=grid[ch][cw]-1
end=grid[dh][dw]-1
if start==end:
    print(0)
    exit()
es=[set([]) for _ in range(col)]
visited=[-1]*col

for i in range(h):
    for j in range(w):
        now=grid[i][j]
        if now!=-1: 
            for x in range(-2, 3):
                for y in range(-2, 3):
                    if 0<=i+x<h and 0<=j+y<w:
                        nex=grid[i+x][j+y]
                        if nex!=-1 and now!=nex:
                            es[now-1].add(nex-1)

stack=deque([start])
visited[start]=0
while stack:
    now=stack.popleft()
    for e in es[now]:
        if visited[e]==-1:
            visited[e]=visited[now]+1
            stack.append(e)

print(visited[end])

Solution (Python):

from collections import deque
def resolve():
    drc4 = [(0, 1), (0, -1), (-1, 0), (1, 0)]
    warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + drc4]

    H, W = map(int, input().split())
    sy, sx = map(lambda x: int(x) - 1, input().split())
    gy, gx = map(lambda x: int(x) - 1, input().split())
    G = [input() for _ in range(H)]

    INF = 10 ** 12
    ans = [[INF] * W for _ in range(H)]

    q = deque()
    q.append((sy, sx, 0))
    ans[sy][sx] = 0

    while q:
        sy, sx, cost = q.popleft()
        for dy, dx in drc4:
            ny = dy + sy
            nx = dx + sx
            if 0 <= ny < H and 0 <= nx < W and G[ny][nx] == "." and ans[ny][nx] > cost:
                ans[ny][nx] = cost
                
                q.appendleft((ny, nx, cost))

        for dy8, dx8 in warp:
            ny8 = dy8 + sy
            nx8 = dx8 + sx
            if 0 <= ny8 < H and 0 <= nx8 < W and G[ny8][nx8] == "." and ans[ny8][nx8] > cost + 1:
                ans[ny8][nx8] = cost + 1
                
                q.append((ny8, nx8, cost + 1))

    res = ans[gy][gx] if ans[gy][gx] < INF else -1
    print(res)


if __name__ == "__main__":
    resolve()

Solution (Python):
H,W = map(int,input().split())
sy,sx = map(int,input().split())
gy,gx = map(int,input().split())
sy,sx = sy-1,sx-1
gy,gx = gy-1,gx-1
S = [input() for i in range(H)]

from collections import deque
INF = float('inf')
dist = [[INF]*W for _ in range(H)]
dist[sy][sx] = 0
q = deque([(sx,sy)])
while q:
    x,y = q.popleft()
    for dx in range(-2,3):
        for dy in range(-2,3):
            if dx == dy == 0: continue
            nx,ny = x+dx,y+dy
            if not 0 <= nx < W: continue
            if not 0 <= ny < H: continue
            if S[ny][nx] == '
            if abs(dx)+abs(dy) <= 1:
                if dist[ny][nx] <= dist[y][x]: continue
                q.appendleft((nx,ny))
                dist[ny][nx] = dist[y][x]
            else:
                if dist[ny][nx] <= dist[y][x] + 1: continue
                q.append((nx,ny))
                dist[ny][nx] = dist[y][x] + 1

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

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())
maze = [input() for _ in range(H)]

INF = 10 ** 12
path = [[INF] * W for _ in range(H)]  


walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]

q = deque()
path[Ch][Cw] = 0
q.append((Ch, Cw, 0))

while q:
    x, y, s = q.popleft()
    for dx, dy in walk:  
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s:
            path[nx][ny] = s
            q.appendleft((nx, ny, s))  
    for dx, dy in warp:  
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s + 1:
            path[nx][ny] = s + 1
            q.append((nx, ny, s + 1))  
    
ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
print(ans)

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


def read(INF=10**7):
    H, W = map(int, input().strip().split())
    CH, CW = map(int, input().strip().split())
    DH, DW = map(int, input().strip().split())
    S = [[0 for j in range(W)] for i in range(H)]
    for i in range(H):
        s = list(input().strip())
        for j in range(W):
            if s[j] == "
                S[i][j] = -2
            else:
                S[i][j] = INF
    return H, W, CH, CW, DH, DW, S


def solve(H, W, CH, CW, DH, DW, S, INF=10**7):
    DIR0 = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    DIR1 = [
        (-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)
    ]
    S[CH-1][CW-1] = 0
    
    q = []
    heapq.heappush(q, (0, CH-1, CW-1))
    while q:
        
        d0, y0, x0 = heapq.heappop(q)
        
        for dy, dx in DIR0:
            ny, nx = y0 + dy, x0 + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] > d0:
                heapq.heappush(q, (d0, ny, nx))
                S[ny][nx] = d0
        
        for dy, dx in DIR1:
            ny, nx = y0 + dy, x0 + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] > d0+1:
                heapq.heappush(q, (d0+1, ny, nx))
                S[ny][nx] = d0+1
    return S[DH-1][DW-1] if S[DH-1][DW-1] != INF else -1


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Solution (Python):

from collections import deque

H, W = map(int, input().split())
C_h, C_w = map(int, input().split())
D_h, D_w = map(int, input().split())
X = [input() for _ in range(H)]

inf = 10 ** 9
dist = [[inf] * W for _ in range(H)]
dist[C_h - 1][C_w - 1] = 0
q = deque()
q.append((C_h - 1, C_w - 1))


while q:
    u, v = q.popleft()
    for i, j in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        if (0 <= u + i < H and 0 <= v + j < W
                and X[u + i][v + j] == "."
                and dist[u + i][v + j] > dist[u][v]):
            dist[u + i][v + j] = dist[u][v]
            q.appendleft((u + i, v + j))

    for i in range(-2, 3):
        for j in range(-2, 3):
            if (0 <= u + i < H and 0 <= v + j < W
                    and X[u + i][v + j] == "."
                    and dist[u + i][v + j] > dist[u][v] + 1):
                dist[u + i][v + j] = dist[u][v] + 1
                q.append((u + i, v + j))

if dist[D_h - 1][D_w - 1] < inf:
    print(dist[D_h - 1][D_w - 1])
else:
    print(-1)

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

from collections import deque

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

S = []
for _ in range(H):
  S.append(list(input()))
  
dpat = ((-1,0),(1,0),(0,-1),(0,1))
mpat = []
for i in range(-2,3):
  for j in range(-2,3):
    if (i,j) in dpat:
      continue
    if i == j and j == 0:
      continue
    mpat.append((i,j))
                



visited = [[False] * W for _ in range(H)]
willSearch = [[False] * W for _ in range(H)]
Q = deque()
QN = deque()
Q.append((0,Ch,Cw))
QN.append((0,Ch,Cw))
while Q:
  while Q:
    c,x,y = Q.popleft()
    if visited[x][y]:
      continue
    visited[x][y] = True
    QN.append((c,x,y))
    
    if x == Dh and y == Dw:
      print(c)
      exit(0)
    for dx,dy in dpat:
      nx,ny = x+dx, y+dy
      if 0<=nx<H and 0<=ny<W:
        if S[nx][ny] == "
          continue
        if visited[nx][ny] or willSearch[nx][ny]:
          continue
        Q.append((c,nx,ny))
        QN.append((c,nx,ny))
        willSearch[nx][ny] = True
  while QN:
    c,x,y = QN.popleft()
    for dx,dy in mpat:
      nx,ny = x+dx, y+dy
      if 0<=nx<H and 0<=ny<W:
        if S[nx][ny] == "
          continue
        if visited[nx][ny] or willSearch[nx][ny]:
          continue
        Q.append((c+1,nx,ny))
        
        
      
print(-1)

Solution (Python):

from collections import deque
def resolve():
    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())
    maze = [input() for _ in range(H)]

    INF = 10 ** 12
    path = [[INF] * W for _ in range(H)]

    q = deque()
    path[Ch][Cw] = 0
    q.append((Ch, Cw, 0))

    walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
    warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]

    while q:
        x, y, s = q.popleft()
        for dx, dy in walk:
            nx = x + dx
            ny = y + dy
            if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s:
                path[nx][ny] = s
                q.appendleft((nx, ny, s))
        for dx, dy in warp:
            nx = x + dx
            ny = y + dy
            if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s + 1:
                path[nx][ny] = s + 1
                q.append((nx, ny, s + 1))

    ans = path[Dh][Dw] if path[Dh][Dw] < INF else -1
    print(ans)


if __name__ == "__main__":
    resolve()

Solution (Python):







from collections import deque

H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh_, dw_ = map(int, input().split())

fs = []
for i in range(H):
    r = list(input())
    fs.append(r)

walks = [(-1,0),(1,0),(0,1),(0,-1)]
magics = []
for i in range(-2,3):
    for j in range(-2,3):
        if i==j==0:continue
        if (i,j) not in walks:
            magics.append((i,j))

INF = 1 << 50
dps = [[INF]*W for i in range(H)]
dps[ch-1][cw-1] = 0
q = deque([])
q.appendleft(((ch-1)*INF+(cw-1),0))
while len(q)>0:
    n,cnt = q.popleft()
    h,w = divmod(n, INF)
    if cnt > dps[h][w]:continue
    dps[h][w] = cnt
    
    for dh, dw in walks:
        hn = h + dh
        wn = w + dw
        if 0<=hn<H and 0<=wn<W:
            if dps[hn][wn] != INF:continue
            if fs[hn][wn] == ".":
                q.appendleft((hn*INF+wn, cnt))
    
    for dh, dw in magics:
        hn = h + dh
        wn = w + dw
        if 0<=hn<H and 0<=wn<W:
            if dps[hn][wn] != INF:continue
            if fs[hn][wn] == ".":
                q.append((hn*INF+wn, cnt+1))

ans = dps[dh_-1][dw_-1]
print(ans if ans != INF else -1)

Solution (Python):

import sys
import collections
import itertools
 
def main():
    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 = [list(input().rstrip()) for _ in range(h)]
    
    que = collections.deque()
    que.append((ch, cw))
    cost = [[float("INF")] * w for _ in range(h)]
    cost[ch][cw] = 0
    
    while que:
        py, px = que.popleft()
        for dy, dx in itertools.product(range(-2, 3), repeat = 2):
            ny, nx = py + dy, px + dx
            if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == ".":
                if dy == dx == 0:
                    continue
                if (dy, dx) in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
                    if cost[ny][nx] > cost[py][px]:
                        cost[ny][nx] = cost[py][px]
                        que.appendleft((ny, nx))
                else:
                    if cost[ny][nx] > cost[py][px] + 1:
                        cost[ny][nx] = cost[py][px] + 1
                        que.append((ny, nx))
                        
    if cost[dh][dw] == float("INF"):
        print(-1)
    else:
        print(cost[dh][dw])
    
if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
"""
01-BFS
"""

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
area = [list(input()) for _ in range(h)]
inf = 10**100
dist = [[inf]*w for i in range(h)]
dwalk = [(0, 1), (0, -1), (1, 0), (-1, 0)]

q = deque([(ch, cw)])
dist[ch][cw] = 0
while q:
    y, x = q.popleft()
    for dy, dx in dwalk:
        py = y+dy; px = x+dx
        if not 0<=py<h: continue
        if not 0<=px<w: continue
        if area[py][px]=='
        if dist[py][px]>dist[y][x]:
            dist[py][px] = dist[y][x]
            q.appendleft((py, px))
    for dy in range(-2, 3):
        for dx in range(-2, 3):
            py = y+dy; px = x+dx
            if not 0<=py<h: continue
            if not 0<=px<w: continue
            if area[py][px]=='
            if dist[py][px]>dist[y][x]+1:
                dist[py][px] = dist[y][x]+1
                q.append((py, px))

if dist[dh][dw] == inf:
    print(-1)
else:
    print(dist[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())
ch-=1; cw-=1; dh-=1; dw-=1
area = [list(input()) for _ in range(h)]
inf = 10**100
dist = [[inf]*w for i in range(h)]
dwalk = [(0, 1), (0, -1), (1, 0), (-1, 0)]

q = deque([(ch, cw)])
dist[ch][cw] = 0
while q:
    y, x = q.popleft()
    for dy, dx in dwalk:
        py = y+dy; px = x+dx
        if not 0<=py<h: continue
        if not 0<=px<w: continue
        if area[py][px]=='
        if dist[py][px]>dist[y][x]:
            dist[py][px] = dist[y][x]
            q.appendleft((py, px))
    for dy in range(-2, 3):
        for dx in range(-2, 3):
            py = y+dy; px = x+dx
            if not 0<=py<h: continue
            if not 0<=px<w: continue
            if area[py][px]=='
            if dist[py][px]>dist[y][x]+1:
                dist[py][px] = dist[y][x]+1
                q.append((py, px))

if dist[dh][dw] == inf:
    print(-1)
else:
    print(dist[dh][dw])

Solution (Python):
from collections import deque
import sys
sys.setrecursionlimit(1000000)

H,W = map(int,input().split())
curX,curY = map(int,input().split())
curX -= 1
curY -= 1
goalX,goalY =  map(int,input().split())
goalX -= 1
goalY -= 1

graph = [ list(input()) for _ in range(H) ]
q = deque([(curX,curY)])
dist = [ [float('inf')]*W for _ in range(H) ]
dist[curX][curY] = 0

while q:
  r,c = q.popleft()
  if r==goalX and c==goalY: break
  hop = dist[r][c]

  
  for x,y in [(1,0),(-1,0),(0,1),(0,-1)]:
    nr,nc = r+x,c+y
    if 0<=nr<H and 0<=nc<W and graph[nr][nc]!="
      dist[nr][nc] = hop
      q.appendleft((nr,nc))

  for i in range(-2, 3):
    for j in range(-2, 3):
      nr,nc = r+i,c+j
      if 0<=nr<H and 0<=nc<W and graph[nr][nc]!="
        dist[nr][nc] = hop+1
        q.append((nr,nc))

ans = dist[goalX][goalY]
if ans == float('inf'):
  print(-1)
else:
  print(ans)

Solution (Python):

import sys
import collections
import itertools

def main():
    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 = [list(input().rstrip()) for _ in range(h)]
    
    que = collections.deque()
    que.append((ch, cw))
    cost = [[float("INF")] * w for _ in range(h)]
    cost[ch][cw] = 0
    
    while que:
        py, px = que.popleft()
        for dy, dx in itertools.product(range(-2, 3), repeat = 2):
            ny, nx = py + dy, px + dx
            if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == ".":
                if dy == dx == 0:
                    continue
                if (dy, dx) in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
                    if cost[ny][nx] > cost[py][px]:
                        cost[ny][nx] = cost[py][px]
                        que.appendleft((ny, nx))
                else:
                    if cost[ny][nx] > cost[py][px] + 1:
                        cost[ny][nx] = cost[py][px] + 1
                        que.append((ny, nx))
                        
    if cost[dh][dw] == float("INF"):
        print(-1)
    else:
        print(cost[dh][dw])
    
if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

"""
ダイクストラ　ギリギリ
"""
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
area = [list(input()) for _ in range(h)]
inf = 10**100
dist = [[inf]*w for i in range(h)]

dwalk = [(0, 1), (0, -1), (1, 0), (-1, 0)]

def Dijkstra(ch, cw):
    import heapq
    edgelist = [(0, ch, cw)]
    heapq.heapify(edgelist)
    dist[ch][cw] = 0
    while len(edgelist):
        cost, y, x = heapq.heappop(edgelist)
        if y==dh and x==dw:
            return dist
        
        if dist[y][x] < cost: continue
        for next_y, next_x in dwalk:
            if 0<=y+next_y<h and 0<=x+next_x<w:
                if area[y+next_y][x+next_x]=='
                if dist[y+next_y][x+next_x]>cost:
                    dist[y+next_y][x+next_x] = cost
                    heapq.heappush(edgelist, (cost, y+next_y, x+next_x))
        for next_y in range(-2, 3):
            for next_x in range(-2, 3):
                    if 0<=y+next_y<h and 0<=x+next_x<w:
                        if area[y+next_y][x+next_x]=='
                        if dist[y+next_y][x+next_x]>cost+1:
                            dist[y+next_y][x+next_x] = cost+1
                            heapq.heappush(edgelist, (cost+1, y+next_y, x+next_x))
    return dist

dist = Dijkstra(ch, cw)
if dist[dh][dw] == inf:
    print(-1)
else:
    print(dist[dh][dw])

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline
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
area = [list(input()) for _ in range(h)]
inf = 10**100
dist = [[inf]*w for i in range(h)]

dwalk = [(0, 1), (0, -1), (1, 0), (-1, 0)]

def Dijkstra(ch, cw):
    import heapq
    edgelist = [(0, ch, cw)]
    heapq.heapify(edgelist)
    dist[ch][cw] = 0
    while len(edgelist):
        cost, y, x = heapq.heappop(edgelist)
        if y==dh and x==dw:
            return dist
        if dist[y][x] < cost: continue
        for next_y, next_x in dwalk:
            if 0<=y+next_y<h and 0<=x+next_x<w:
                if area[y+next_y][x+next_x]=='
                if dist[y+next_y][x+next_x]>cost:
                    dist[y+next_y][x+next_x] = cost
                    heapq.heappush(edgelist, (cost, y+next_y, x+next_x))
        for next_y in range(-2, 3):
            for next_x in range(-2, 3):
                    if 0<=y+next_y<h and 0<=x+next_x<w:
                        if area[y+next_y][x+next_x]=='
                        if dist[y+next_y][x+next_x]>cost+1:
                            dist[y+next_y][x+next_x] = cost+1
                            heapq.heappush(edgelist, (cost+1, y+next_y, x+next_x))
    return dist

dist = Dijkstra(ch, cw)
if dist[dh][dw] == inf:
    print(-1)
else:
    print(dist[dh][dw])

Solution (Python):
from collections import deque

class UnionFind:
    def __init__(self, size):
        self.parent = list(range(size))
        self.height = [0] * size
        self.size = [1] * size
        self.componentCount = size

    def root(self, index):
        if self.parent[index] == index:  
            return index
        rootIndex = self.root(self.parent[index])  
        self.parent[index] = rootIndex  
        return rootIndex

    def union(self, index1, index2):  
        root1 = self.root(index1)
        root2 = self.root(index2)

        if root1 == root2:  
            return

        self.componentCount -= 1  

        if self.height[root1] < self.height[root2]:
            self.parent[root1] = root2  
            self.size[root2] += self.size[root1]
        else:
            self.parent[root2] = root1  
            self.size[root1] += self.size[root2]
            if self.height[root1] == self.height[root2]:
                self.height[root1] += 1
        return

    def isSameRoot(self, index1, index2):
        return self.root(index1) == self.root(index2)

    def sizeOfSameRoot(self, index):
        return self.size[self.root(index)]

H, W = map(int, input().split())
C = tuple(map(int, input().split()))
D = tuple(map(int, input().split()))
S = [input() for _ in range(H)]

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

tree = UnionFind(H * W + 100)

for h in range(H):
    for w in range(W):
        if S[h][w] == '
            continue

        for dh, dw in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            toH, toW = h + dh, w + dw

            if 0 <= toH < H and 0 <= toW < W and S[toH][toW] == '.':
                tree.union(cord(h, w), cord(toH, toW))

roots = [tree.root(i) for i in range(H * W)]
M = max(roots) + 1
edges = [set() for _ in range(M)]

def search(h, w):
    for dh in range(-2, 3):
        for dw in range(-2, 3):
            toH, toW = h + dh, w + dw
            if 0 <= toH < H and 0 <= toW < W and S[toH][toW] == '.':
                if roots[cord(h, w)] == roots[cord(toH, toW)]:
                    continue
                edges[roots[cord(h, w)]].add(roots[cord(toH, toW)])

for h in range(H):
    for w in range(W):
        if S[h][w] == '
            continue
        search(h, w)

edges = [list(e) for e in edges]

S = roots[cord(C[0] - 1, C[1] - 1)]
T = roots[cord(D[0] - 1, D[1] - 1)]

INF = 10**18
que = deque([(S, 0)])
minDist = [INF] * M
minDist[S] = 0

while que:
    now, dist = que.popleft()

    for to in edges[now]:
        if minDist[to] > dist + 1:
            minDist[to] = dist + 1
            que.append((to, dist + 1))

print(minDist[T] if minDist[T] < INF else -1)