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
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap



def slv(H, W, C, D, S):
    C = (C[0]-1, C[1]-1)
    D = (D[0]-1, D[1]-1)
    q = deque()
    q.append((0, C))
    memo = {}
    T = 10**6
    while q:
        c, (x, y) = q.popleft()
        v = x*T + y
        if v in memo:
            continue
        memo[v] = c

        for nx in range(x-2, x+3):
            for ny in range(y-2, y+3):
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                    d = abs(nx-x) + abs(ny-y)
                    if d == 1:
                        q.appendleft((c, (nx, ny)))
                    elif d == 0:
                        pass
                    else:
                        q.append((c+1, (nx, ny)))
    g = D[0]*T + D[1]
    return -1 if g not in memo else memo[g]


def main():
    H, W = read_int_n()
    C = read_int_n()
    D = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, C, D, S))


if __name__ == '__main__':
    main()

Solution (Python):

from collections import deque

import sys
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap



def slv(H, W, C, D, S):
    C = (C[0]-1, C[1]-1)
    D = (D[0]-1, D[1]-1)
    q = deque()
    q.append((0, C))
    memo = {}
    T = 10**6
    while q:
        c, (x, y) = q.popleft()
        v = x*T + y
        if v in memo:
            continue
        memo[v] = c

        for nx in range(x-2, x+3):
            for ny in range(y-2, y+3):
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                    if abs(nx-x) + abs(ny-y) == 1:
                        q.appendleft((c, (nx, ny)))
                    else:
                        q.append((c+1, (nx, ny)))
    g = D[0]*T + D[1]
    return -1 if g not in memo else memo[g]


def main():
    H, W = read_int_n()
    C = read_int_n()
    D = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, C, D, S))


if __name__ == '__main__':
    main()

Solution (Python):
H, W = map(int, input().split())
ch, cw =  map(int, input().split())
gh, gw =  map(int, input().split())

f = [[s=="." for s in input()] for h in range(H)]
ans = [[-1 for w in range(W)]for h in range(H)]

nextQ = [(ch-1)*1000 + cw-1]
ans[ch-1][cw-1] = 0
while len(nextQ)>0:
  Q = list(nextQ)
  nextQ = set()
  visited = set()
  while len(Q):
    nh = Q.pop(0)
    nw = nh%1000
    nh = nh//1000
    for dh in range(0-min(nh,2), 3):
      if nh+dh>=H:
        break
      for dw in range(0-min(nw,2), 3):
        if nw + dw>=W:
          break
        if dh==0 and dw==0:
          continue
        if dh*dw==0 and (abs(dh)==1 or abs(dw)==1):
          if ans[nh+dh][nw+dw]==-1:
            if f[nh+dh][nw+dw]:
              Q.append((nh+dh)*1000 + nw+dw)
              visited.add((nh+dh)*1000 + nw+dw)
              ans[nh+dh][nw+dw]=ans[nh][nw]
            else:
              ans[nh+dh][nw+dw]=-2
          elif ans[nh+dh][nw+dw]>ans[nh][nw]:
            Q.append((nh+dh)*1000 + nw+dw)
            visited.add((nh+dh)*1000 + nw+dw)
            ans[nh+dh][nw+dw]=ans[nh][nw]
        else:
          if ans[nh+dh][nw+dw]==-1:
            if f[nh+dh][nw+dw]:
              nextQ.add((nh+dh)*1000 + nw+dw)
              ans[nh+dh][nw+dw]=ans[nh][nw]+1
            else:
              ans[nh+dh][nw+dw]=-2
          elif ans[nh+dh][nw+dw]>ans[nh][nw]:
            nextQ.add((nh+dh)*1000 + nw+dw)
            ans[nh+dh][nw+dw]=ans[nh][nw]+1
  nextQ -= visited
print(ans[gh-1][gw-1])

Solution (Python):

from collections import deque

import sys
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(H, W, C, D, S):
    C = (C[0]-1, C[1]-1)
    D = (D[0]-1, D[1]-1)
    q = deque()
    q.append((0, C))
    memo = {}
    T = 10**6
    while q:
        c, (x, y) = q.popleft()
        v = x*T + y
        if v in memo:
            continue
        memo[v] = c

        for nx in range(x-2, x+3):
            for ny in range(y-2, y+3):
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                    if abs(nx-x) + abs(ny-y) == 1:
                        q.appendleft((c, (nx, ny)))
                    else:
                        q.append((c+1, (nx, ny)))
    g = D[0]*T + D[1]
    return -1 if g not in memo else memo[g]


def main():
    H, W = read_int_n()
    C = read_int_n()
    D = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, C, D, S))


if __name__ == '__main__':
    main()

Solution (Python):

from collections import deque


def main():
    h, w = map(int, input().split())
    ch, cw = map(int, input().split())
    dh, dw = map(int, input().split())

    """
    l = [list(input().strip()) for i in range(h)]
    ans = [[-1]*w for i in range(h)]
    for i in range(h):
        for j in range(w):
            if l[i][j] == "
                ans[i][j] = -2
    ch -= 1
    cw -= 1
    dh -= 1
    dw -= 1
    """

    base = ["
    base.append("
    for n in range(h):
        base.append("
    base.append("
    base.append("
    ans = [[-1] * (w + 4) for _ in range(h + 4)]
    for i in range(h + 4):
        for j in range(w + 4):
            if base[i][j] == "
                ans[i][j] = -2
    ch += 1
    cw += 1
    dh += 1
    dw += 1
    
    ans[ch][cw] = 0
    move1 = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    move2 = [
        [-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]
    ]
    q1 = deque([[ch, cw]])
    q2 = deque([])

    while q1:
        x1, y1 = q1.popleft()
        q2.append([x1, y1])
        for i, j in move1:
            nx, ny = x1 + i, y1 + j
            """
            if nx < 0 or h <= nx or ny < 0 or w <= ny:
                continue
            """
            if ans[nx][ny] == -1:
                ans[nx][ny] = ans[x1][y1]
                q1.append([nx, ny])
        if len(q1) == 0:
            while q2:
                x2, y2 = q2.popleft()
                for i, j in move2:
                    mx, my = x2 + i, y2 + j
                    """
                    if mx < 0 or h <= mx or my < 0 or w <= my:
                        continue
                    """
                    if ans[mx][my] == -1:
                        ans[mx][my] = ans[x2][y2] + 1
                        q1.append([mx, my])
    print(ans[dh][dw])


if __name__ == "__main__":
    main()

Solution (Python):

import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys


buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(H, W, C, D, S):
    C = (C[0]-1, C[1]-1)
    D = (D[0]-1, D[1]-1)
    q = deque()
    q.append((0, C))
    memo = {}
    T = 10**6
    while q:
        c, (x, y) = q.popleft()
        if (x*T + y) in memo:
            continue
        memo[x*T + y] = c

        for nx in range(x-2, x+3):
            for ny in range(y-2, y+3):
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                    if abs(nx-x) + abs(ny-y) == 1:
                        q.appendleft((c, (nx, ny)))
                    else:
                        q.append((c+1, (nx, ny)))
    g = D[0]*T + D[1]
    return -1 if g not in memo else memo[g]


def main():
    H, W = read_int_n()
    C = read_int_n()
    D = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, C, D, S))


if __name__ == '__main__':
    main()

Solution (Python):

from collections import deque


def main():
    h, w = map(int, input().split())
    ch, cw = map(int, input().split())
    dh, dw = map(int, input().split())

    """
    l = [list(input().strip()) for i in range(h)]
    ans = [[-1]*w for i in range(h)]
    for i in range(h):
        for j in range(w):
            if l[i][j] == "
                ans[i][j] = -2
    ch -= 1
    cw -= 1
    dh -= 1
    dw -= 1
    """

    base = ["
    base.append("
    for n in range(h):
        base.append("
    base.append("
    base.append("
    ans = [[-1] * (w + 4) for _ in range(h + 4)]
    for i in range(h + 4):
        for j in range(w + 4):
            if base[i][j] == "
                ans[i][j] = -2
    ch += 1
    cw += 1
    dh += 1
    dw += 1

    ans[ch][cw] = 0
    move1 = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    move2 = [
        [-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]
    ]
    q1 = deque([[ch, cw]])
    q2 = deque([])

    while q1:
        x1, y1 = q1.popleft()
        q2.append([x1, y1])
        for i, j in move1:
            nx, ny = x1 + i, y1 + j
            """
            if nx < 0 or h <= nx or ny < 0 or w <= ny:
                continue
            """
            if ans[nx][ny] == -1:
                ans[nx][ny] = ans[x1][y1]
                q1.append([nx, ny])
        if len(q1) == 0:
            while q2:
                x2, y2 = q2.popleft()
                for i, j in move2:
                    mx, my = x2 + i, y2 + j
                    """
                    if mx < 0 or h <= mx or my < 0 or w <= my:
                        continue
                    """
                    if ans[mx][my] == -1:
                        ans[mx][my] = ans[x2][y2] + 1
                        q1.append([mx, my])
    print(ans[dh][dw])


if __name__ == "__main__":
    main()

Solution (Python):

import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys


buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(H, W, C, D, S):

    C = (C[0]-1, C[1]-1)
    D = (D[0]-1, D[1]-1)
    q = deque()
    q.append((0, C))
    memo = {}
    T = 10**6
    while q:
        c, (x, y) = q.popleft()
        if (x*T + y) in memo:
            continue
        memo[x*T + y] = c

        for nx in range(x-2, x+3):
            for ny in range(y-2, y+3):
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                    if abs(nx-x) + abs(ny-y) == 1:
                        q.appendleft((c, (nx, ny)))
                    else:
                        q.append((c+1, (nx, ny)))

    return -1 if (D[0]*T + D[1]) not in memo else memo[D[0]*T + D[1]]


def main():
    H, W = read_int_n()
    C = read_int_n()
    D = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, C, D, S))


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

grid=["0"]*H
for i in range(H):
    s=input()
    grid[i]=s

Inf=10**12
cost=[[Inf] * W for i in range(H)] 

walk=[(0, 1), (0, -1), (-1, 0), (1, 0)]
warp=[]

for i in range(-2, 3):
    for j in range(-2, 3):
        if i==0 and j==0:
            continue
        if (i, j) not in walk:
            warp.append((i, j))

q=deque()
cost[ch][cw]=0
q.append((ch, cw, 0))

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


if cost[dh][dw]==Inf:
    print(-1)
else:
    ans=cost[dh][dw]
    print(ans)

Solution (Python):

import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys


buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(H, W, C, D, S):

    C = (C[0]-1, C[1]-1)
    D = (D[0]-1, D[1]-1)
    q = deque()
    q.append((0, C))
    memo = {}
    T = 10**6
    while q:
        c, (x, y) = q.popleft()
        if (x*T + y) in memo:
            continue
        memo[x*T + y] = c
        for nx, ny in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                q.appendleft((c, (nx, ny)))

        for nx in range(x-2, x+3):
            for ny in range(y-2, y+3):
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                    q.append((c+1, (nx, ny)))

    return -1 if (D[0]*T + D[1]) not in memo else memo[D[0]*T + D[1]]


def main():
    H, W = read_int_n()
    C = read_int_n()
    D = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, C, D, S))


if __name__ == '__main__':
    main()

Solution (Python):

import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub


import sys


buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(H, W, C, D, S):

    C = (C[0]-1, C[1]-1)
    D = (D[0]-1, D[1]-1)
    q = deque()
    q.append((0, C))
    memo = {}
    while q:
        c, (x, y) = q.popleft()
        if (x, y) in memo:
            continue
        memo[(x, y)] = c
        for nx, ny in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                q.appendleft((c, (nx, ny)))

        for nx in range(x-2, x+3):
            for ny in range(y-2, y+3):
                if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                    q.append((c+1, (nx, ny)))


    return -1 if tuple(D) not in memo else memo[D]


def main():
    H, W = read_int_n()
    C = read_int_n()
    D = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, C, D, S))


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
def solve():
    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())
    A = [list(input()) for _ in range(H)]
    V = [[-1]*W for _ in range(H)]
    d = ((1,0),(0,1),(-1,0),(0,-1))

    def bfs_2d(sy,sx,v):
        que = deque()
        V[sy][sx] = v
        que.append((sy,sx))

        while que:
            uh, uw = que.popleft()
            for dy, dx in d:
                next_h = uh+dy
                next_w = uw+dx
                if 0 <= next_h < H and 0 <= next_w < W \
                    and A[next_h][next_w] == '.' \
                    and V[next_h][next_w] == -1:
                    V[next_h][next_w] = v
                    que.append((next_h,next_w))
    
    vertex = 0
    for h in range(H):
        for w in range(W):
            if A[h][w] == '
                continue
            bfs_2d(h,w,vertex)
            vertex += 1

    G = [[] for _ in range(vertex)]
    used = [set() for _ in range(vertex)]
    for h in range(H):
        for w in range(W):
            if A[h][w] == '
                continue
            for dh in range(-2, 2+1):
                for dw in range(-2, 2+1):
                    if h + dh < 0 or H <= h + dh or w + dw < 0 or W <= w + dw:
                        continue
                    if A[h+dh][w+dw] == "
                        continue
                    if V[h][w] == V[h+dh][w+dw]:
                        continue
                    if V[h+dh][w+dw] in used[V[h][w]]:
                        continue
                    G[V[h][w]].append((V[h+dh][w+dw]))
                    used[V[h][w]].add((V[h+dh][w+dw]))
    
    s = V[Ch][Cw]
    g = V[Dh][Dw]

    dist = [-1 for _ in range(vertex)]
    que = deque()
    dist[s] = 0
    que.append(s)
    while que:
        u = que.popleft()
        for v in G[u]:
            if dist[v] != -1:
                continue
            dist[v] = dist[u] + 1
            que.append(v)
    
    print(dist[g])

if __name__ == '__main__':
    solve()

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

grid=["0"]*H
for i in range(H):
    s=input()
    grid[i]=s

Inf=10**12
cost=[[Inf] * W for i in range(H)]

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

q=deque()
cost[ch][cw]=0
q.append((ch, cw, 0))

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


if cost[dh][dw]==Inf:
    print(-1)
else:
    ans=cost[dh][dw]
    print(ans)

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;
S = []

for _ in range(H):
    S.append(input())

dq = deque()
dq.append((Cw, Ch))

dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]

visited = [[-1 for _ in range(W)] for _ in range(H)]
visited[Ch][Cw] = 0
while dq:
    x, y = dq.popleft()

    
    for dx_, dy_ in zip(dx, dy):
        if (not 0 <= x+dx_ < W) or (not 0 <= y+dy_ < H):
            continue
        if S[y+dy_][x+dx_] == "
            continue
        
        if visited[y+dy_][x+dx_] == -1 or visited[y+dy_][x+dx_] > visited[y][x]:
            visited[y+dy_][x+dx_] = visited[y][x]
            dq.appendleft((x+dx_, y+dy_))

    for i in range(-2, 3):
        for j in range(-2, 3):
            if (not 0 <= x+i < W) or (not 0 <= y+j < H):
                continue
            if S[y+j][x+i] == '
                continue

            if visited[y+j][x+i] == -1:
                visited[y+j][x+i] = visited[y][x] + 1
                dq.append((x+i, y+j))

ans = visited[Dh][Dw]
print(ans)

Solution (Python):
from collections import deque
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
INF=float("inf")

H,W=map(int,readline().split())
Ch,Cw=map(lambda x: int(x) - 1, readline().split())
Dh,Dw=map(lambda x: int(x) - 1, readline().split())
maze=list(map(str,read().rstrip().decode().split()))

path=[[INF]*W for _ in range(H)]
walk=[(1,0),(0,-1),(-1,0),(0,1)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if not (i, j) 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):
from collections import deque

def resolve():
    H,W = map(int,input().split())
    Sy,Sx = [int(i)-1 for i in input().split()]
    Gy,Gx = [int(i)-1 for i in input().split()]

    MP = [input() for i in range(H)]
    q =[]
    mxxx = 10**10
    score=[[mxxx]*W  for i in range(H)]
    score[Sy][Sx] = 0
    deq = deque()
    deq.append((Sy,Sx))
    unvisited=set()
    for y,row in enumerate(MP):
        for x,i in enumerate(row):
            if i ==".":
                unvisited.add((y,x))

    while deq:
        y,x = deq.popleft()
        if not (y,x) in unvisited:
            continue
        unvisited.remove((y,x))

        if (y-1,x) in unvisited and score[y-1][x]>score[y][x]:
            score[y-1][x]=score[y][x]
            deq.appendleft((y-1,x))
        if (y+1,x) in unvisited and score[y+1][x]>score[y][x]:
            score[y+1][x]=score[y][x]
            deq.appendleft((y+1,x))
        if (y,x-1) in unvisited and score[y][x-1]>score[y][x]:
            score[y][x-1]=score[y][x]
            deq.appendleft((y,x-1))
        if (y,x+1) in unvisited and score[y][x+1]>score[y][x]:
            score[y][x+1]=score[y][x]
            deq.appendleft((y,x+1))

        for i in range(y-2,y+3):
            for j in range(x-2,x+3):
                if (i,j) in unvisited and score[i][j] > score[y][x]+1:
                    score[i][j] = score[y][x]+1
                    deq.append((i,j))
    
    if score[Gy][Gx] == 10**10:
        print(-1)
    else:
        print(score[Gy][Gx])




    
resolve()

Solution (Python):

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


class WarpableMaze:
    __slots__ = ["height", "width", "road", "wall", "grid"]

    def __init__(
        self,
        height: int,
        width: int,
        grid: List[str],
        road: str = ".",
        wall: str = "
    ) -> None:
        
        self.height = height + 4
        self.width = width + 4
        self.road = road
        self.wall = wall
        self.grid = self._flatten_grid(grid)

    def _flatten_grid(self, grid: List[str]) -> str:
        flat_grid = self.wall * self.width * 2
        for row in grid:
            flat_grid += self.wall * 2 + row + self.wall * 2
        flat_grid += self.wall * self.width * 2
        return flat_grid

    def _flatten_dxy(self, x: int, y: int) -> int:
        return self.width * x + y

    def _flatten_coordinate(self, h: int, w: int) -> int:
        return self._flatten_dxy(h + 2, w + 2)

    def bfs(self, start_2d: Tuple[int, int], goal_2d: Tuple[int, int]) -> int:
        start = self._flatten_coordinate(*start_2d)
        goal = self._flatten_coordinate(*goal_2d)

        w = self.width
        flatten = lambda *dxy: tuple(self._flatten_dxy(*xy) for xy in dxy)
        move_to_warp = {
            -w: flatten((-2, -2), (-2, -1), (-2, 0), (-2, 1), (-1, -1)),
            w: flatten((1, 1), (2, -1), (2, 0), (2, 1), (2, 2)),
            -1: flatten((-1, -2), (0, -2), (1, -2), (1, -1), (2, -2)),
            1: flatten((-1, 1), (-2, 2), (-1, 2), (0, 2), (1, 2)),
        }

        unsearched = 1 << 30
        dist = [unsearched] * (self.height * self.width)
        dist[start] = 0
        queue = deque([start])
        while queue:
            x = queue.popleft()
            cur_dist = dist[x]
            if x == goal:
                break

            for move, warp in move_to_warp.items():
                nx = x + move
                if self.grid[nx] == self.road:
                    if dist[nx] > cur_dist:
                        dist[nx] = cur_dist
                        queue.appendleft(nx)
                    continue

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

        return dist[goal] if dist[goal] != unsearched else -1

    def debug(self):
        print("<DEBUG>", file=sys.stderr)
        for row in zip(*[iter(self.grid)] * self.width):
            print(*row, file=sys.stderr)


def main():
    H, W, CH, CW, DH, DW, *S = open(0).read().split()
    maze = WarpableMaze(int(H), int(W), S)
    start, goal = (int(CH) - 1, int(CW) - 1), (int(DH) - 1, int(DW) - 1)
    print(maze.bfs(start, goal))
    


if __name__ == "__main__":
    main()