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



Sample input:
4 4
1 1
4 4
..#.
..#.
.#..
.#..


Sample output:
1

Submission status: Accepted

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

########################################################################################################################################################################
# Verified by
# https://atcoder.jp/contests/arc033/submissions/me
# https://atcoder.jp/contests/abc174/tasks/abc174_f
#
# speed up TIPS: delete update of el. non-use of getitem, setitem.
#
# Binary Indexed Tree
# Bit.add(i,x)    : add x at i-th value
# Bit.sum(i)      : get sum up to i-th value
# Bit.l_bound(w)  : get bound of index where x1+x2+...+xi<w

class Bit: # 1-indexed
    def __init__(self,n,init=None):
        self.size=n
        self.m=len(bin(self.size))-2
        self.arr=[0]*(2**self.m+1)
        self.el=[0]*(2**self.m+1)
        if init!=None:
            for i in range(len(init)):
                self.add(i,init[i])
                self.el[i]=init[i]

    def __str__(self):
        a=[self.sum(i+1)-self.sum(i) for i in range(self.size)]
        return str(a)
        
    def add(self,i,x):
        if not 0<i<=self.size:return NotImplemented
        self.el[i]+=x
        while i<=self.size:
            self.arr[i]+=x
            i+=i&(-i)
        return
    
    def sum(self,i):
        if not 0<=i<=self.size:return NotImplemented
        rt=0
        while i>0:
            rt+=self.arr[i]
            i-=i&(-i)
        return rt
    
    def __getitem__(self,key):
        return self.el[key]
        return self.sum(key+1)-self.sum(key)

    def __setitem__(self,key,value):
        self.add(key,value-self.sum(key+1)+self.sum(key))

    def l_bound(self,w):
        if w<=0:
            return 0
        x=0
        k=2**self.m
        while k>0:
            if x+k<=self.size and self.arr[x+k]<w:
                w-=self.arr[x+k]
                x+=k
            k>>=1
        return x+1
        
    def u_bound(self,w):
        if w<=0:
            return 0
        x=0
        k=2**self.m
        while k>0:
            if x+k<=self.size and self.arr[x+k]<=w:
                w-=self.arr[x+k]
                x+=k
            k>>=1
        return x+1
        
class Bit0(Bit): # 0-indexed
    def add(self,j,x):
        super().add(j+1,x)
    def l_bound(self,w):
        return max(super().l_bound(w)-1,0)
    def u_bound(self,w):
        return max(super().u_bound(w)-1,0)

class Multiset(Bit0):
    def __init__(self,max_v):
        super().__init__(max_v)
    def insert(self,x):
        super().add(x,1)
    def find(self,x):
        return super().l_bound(super().sum(x))
    def __str__(self):
        return str(self.arr)

def compress(L):
    dc={v:i for i,v in enumerate(sorted(set(L)))}
    return [dc[i] for i in L]


show_flg=False
show_flg=True

ans=0

h,w=LI()
sh,sw=LI()
gh,gw=LI()

w+=2
m=[1]*w
for i in range(h):
    s=input()
    m+=[1]+[i=='#'for i in s]+[1]
m+=[1]*w
h+=2
n=h*w
v=[-1]*w*h

dc=dict()
cn=0
def bfs(x):
    global cn
    q=[x]
    v[x]=x
    dc[x]=cn
    cn+=1
    while q:
        c=q.pop()
        for nx in [c+1,c-1,c+w,c-w]:
            if 0<=nx<n and m[nx]!=1 and v[nx]==-1:
                q+=nx,
                v[nx]=x
    return        
            
for i in range(n):
    if m[i]!=1 and v[i]==-1:
        bfs(i)

g=[set()for i in range(cn)]
nbw=[-2*w+1,-2*w+2,-w+1,-w+2,2,2*w+1,2*w+2,w+1,w+2,+2*w,-2*w,-2*w-1,-2*w-2,-w-1,-w-2,-2,2*w-1,2*w-2,w-1,w-2]
nb=[1,-1,w,-w]
d=[-1]*n
v=[0]*n
vw=[0]*n
q=deque([sh*w+sw])
d[sh*w+sw]=0
vw[sh*w+sw]=1
while q:
    i=q.pop()
    if m[i]==1:
        continue
    for di in nb:
        nx=i+di
        if 0<=nx<n and m[nx]!=1 and (d[nx]==-1 or d[nx]>d[i]):
            d[nx]=d[i]
            q.append(nx)

    for di in nbw:
        nx=i+di
        if 0<=nx<n and m[nx]!=1 and d[nx]==-1:
            q.appendleft(nx)
            d[nx]=d[i]+1
print(d[gh*w+gw])

Submission status: Accepted

Solution code:
from collections import deque
from itertools import product


def bfs(x, y):
    dist = [[10 ** 9] * w for _ in range(h)]
    dist[y][x] = 0
    que = deque([(x, y)])

    while len(que) > 0:
        x, y = que.popleft()
        near_a = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
        num = product([-2, -1, 0, 1, 2], repeat=2)
        near_b = [(x + dx, y + dy) for dx, dy in num]
        if (x, y) == (Dw - 1, Dh - 1):
            return dist[y][x]

        for cnt, l in enumerate((near_a, near_b)):
            for i, j in l:
                if (0 <= i < w and 0 <= j < h and
                        dist[j][i] > dist[y][x] + cnt and s[j][i] == '.'):
                    dist[j][i] = dist[y][x] + cnt
                    if cnt == 0:
                        que.appendleft((i, j))
                    elif cnt == 1:
                        que.append((i, j))
    return -1


h, w = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
s = [input() for _ in range(h)]

print(bfs(Cw - 1, Ch - 1))

Submission status: Accepted

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range;R=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def RLI(n=8,a=1,b=10):return [random.randint(a,b)for i in range(n)]
def RI(a=1,b=10):return random.randint(a,b)
def Rtest(T):
    case,err=0,0
    for i in range(T):
        inp=INP()
        a1,ls=naive(*inp)
        a2=solve(*inp)
        if a1!=a2:
            print((a1,a2),inp)
            err+=1
        case+=1
    print('Tested',case,'case with',err,'errors')
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in R(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in R(base**n):s=[tb//(base**bt)%base for bt in R(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def YN(x):print(['NO','YES'][x])
def Yn(x):print(['No','Yes'][x])
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**9)
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

########################################################################################################################################################################
# Verified by
# https://atcoder.jp/contests/arc033/submissions/me
# https://atcoder.jp/contests/abc174/tasks/abc174_f
#
# speed up TIPS: delete update of el. non-use of getitem, setitem.
#
# Binary Indexed Tree
# Bit.add(i,x)    : add x at i-th value
# Bit.sum(i)      : get sum up to i-th value
# Bit.l_bound(w)  : get bound of index where x1+x2+...+xi<w

class Bit: # 1-indexed
    def __init__(self,n,init=None):
        self.size=n
        self.m=len(bin(self.size))-2
        self.arr=[0]*(2**self.m+1)
        self.el=[0]*(2**self.m+1)
        if init!=None:
            for i in range(len(init)):
                self.add(i,init[i])
                self.el[i]=init[i]

    def __str__(self):
        a=[self.sum(i+1)-self.sum(i) for i in range(self.size)]
        return str(a)
        
    def add(self,i,x):
        if not 0<i<=self.size:return NotImplemented
        self.el[i]+=x
        while i<=self.size:
            self.arr[i]+=x
            i+=i&(-i)
        return
    
    def sum(self,i):
        if not 0<=i<=self.size:return NotImplemented
        rt=0
        while i>0:
            rt+=self.arr[i]
            i-=i&(-i)
        return rt
    
    def __getitem__(self,key):
        return self.el[key]
        return self.sum(key+1)-self.sum(key)

    def __setitem__(self,key,value):
        self.add(key,value-self.sum(key+1)+self.sum(key))

    def l_bound(self,w):
        if w<=0:
            return 0
        x=0
        k=2**self.m
        while k>0:
            if x+k<=self.size and self.arr[x+k]<w:
                w-=self.arr[x+k]
                x+=k
            k>>=1
        return x+1
        
    def u_bound(self,w):
        if w<=0:
            return 0
        x=0
        k=2**self.m
        while k>0:
            if x+k<=self.size and self.arr[x+k]<=w:
                w-=self.arr[x+k]
                x+=k
            k>>=1
        return x+1
        
class Bit0(Bit): # 0-indexed
    def add(self,j,x):
        super().add(j+1,x)
    def l_bound(self,w):
        return max(super().l_bound(w)-1,0)
    def u_bound(self,w):
        return max(super().u_bound(w)-1,0)

class Multiset(Bit0):
    def __init__(self,max_v):
        super().__init__(max_v)
    def insert(self,x):
        super().add(x,1)
    def find(self,x):
        return super().l_bound(super().sum(x))
    def __str__(self):
        return str(self.arr)

def compress(L):
    dc={v:i for i,v in enumerate(sorted(set(L)))}
    return [dc[i] for i in L]


show_flg=False
show_flg=True

ans=0

h,w=LI()
sh,sw=LI()
gh,gw=LI()

w+=2
m=[1]*w
for i in range(h):
    s=input()
    m+=[1]+[i=='#'for i in s]+[1]
m+=[1]*w
h+=2
n=h*w
v=[-1]*w*h

dc=dict()
cn=0
def bfs(x):
    global cn
    q=[x]
    v[x]=x
    dc[x]=cn
    cn+=1
    while q:
        c=q.pop()
        for nx in [c+1,c-1,c+w,c-w]:
            if 0<=nx<n and m[nx]!=1 and v[nx]==-1:
                q+=nx,
                v[nx]=x
    return        
            
for i in range(n):
    if m[i]!=1 and v[i]==-1:
        bfs(i)

g=[set()for i in range(cn)]
nbw=[-2*w+1,-2*w+2,-w+1,-w+2,2,2*w+1,2*w+2,w+1,w+2,+2*w,-2*w,-2*w-1,-2*w-2,-w-1,-w-2,-2,2*w-1,2*w-2,w-1,w-2]
nb=[1,-1,w,-w]
d=[-1]*n
v=[0]*n
vw=[0]*n
q=deque([(sh*w+sw,0)])
v[sh*w+sw]=1
vw[sh*w+sw]=1
while q:
    i,dist=q.pop()
    if d[i]==-1:
        d[i]=dist
    else:
        d[i]=min(dist,d[i])
    if m[i]==1:
        continue
    for di in nb:
        nx=i+di
        if 0<=nx<n and m[nx]!=1 and v[nx]==0:
            #d[nx]=d[i]
            v[nx]=1
            q.append((nx,d[i]))

    for di in nbw:
        nx=i+di
        if 0<=nx<n and m[nx]!=1 and vw[nx]==0:
            vw[nx]=1
            q.appendleft((nx,d[i]+1))
print(d[gh*w+gw])

Submission status: Accepted

Solution code:
from collections import deque
from itertools import product


def bfs(x, y):
    dist = [[10 ** 9] * w for _ in range(h)]
    dist[y][x] = 0
    for i, si in enumerate(s):
        for j, sij in enumerate(si):
            if sij == '#':
                dist[i][j] = -1
    que = deque([(x, y)])

    while len(que) > 0:
        x, y = que.popleft()
        near_a = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
        num = product([-2, -1, 0, 1, 2], repeat=2)
        near_b = [(x + dx, y + dy) for dx, dy in num]

        for cnt, l in enumerate((near_a, near_b)):
            for i, j in l:
                if (0 <= i < w and 0 <= j < h and
                        dist[j][i] > dist[y][x] + cnt and s[j][i] == '.'):
                    dist[j][i] = dist[y][x] + cnt
                    if cnt == 0:
                        que.appendleft((i, j))
                    elif cnt == 1:
                        que.append((i, j))
    return dist


h, w = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
s = [input() for _ in range(h)]

ans = bfs(Cw - 1, Ch - 1)[Dh - 1][Dw - 1]
print(-1 if ans == 10 ** 9 else ans)

Submission status: Accepted

Solution code:
from collections import deque

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

INF = float("INF")
cnt = [[INF]*W for _ in range(H)]

q = deque()
q.append([sy, sx])
cnt[sy][sx] = 0
move = [[1, 0], [-1, 0], [0, 1], [0, -1]]

while q:
    y, x = q.popleft()
    for dy, dx in move:
        ny = y + dy
        nx = x + dx
        if ny < 0 or ny > H-1 or nx < 0 or nx > W-1:
            continue
        if maze[ny][nx] == "." and cnt[ny][nx] > cnt[y][x]:
            cnt[ny][nx] = cnt[y][x]
            q.appendleft([ny, nx])
        for i in range(-2, 2+1):
            for j in range(-2, 2+1):
                wy = y + i
                wx = x + j
                if wy < 0 or wy > H-1 or wx < 0 or wx > W-1:
                    continue
                if maze[wy][wx] == "." and cnt[wy][wx] > cnt[y][x] + 1:
                    cnt[wy][wx] = cnt[y][x] + 1
                    q.append([wy, wx])

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

Submission status: Accepted

Solution code:
from collections import deque
from itertools import product


def bfs(x, y):
    dist = [[10 ** 9] * w for _ in range(h)]
    dist[y][x] = 0
    que = deque([(x,y)])

    while len(que) > 0:
        x, y = que.popleft()
        near_a = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
        num = product([-2, -1, 0, 1, 2], repeat=2)
        near_b = [(x + dx, y + dy) for dx, dy in num]

        for cnt, l in enumerate((near_a, near_b)):
            for i, j in l:
                if (0 <= i < w and 0 <= j < h and
                        dist[j][i] > dist[y][x] + cnt and s[j][i] == '.'):
                    dist[j][i] = dist[y][x] + cnt
                    if cnt == 0:
                        que.appendleft((i, j))
                    elif cnt == 1:
                        que.append((i, j))
    return dist


h, w = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
s = [input() for _ in range(h)]

ans = bfs(Cw - 1, Ch - 1)[Dh - 1][Dw - 1]
print(-1 if ans == 10 ** 9 else ans)

Submission status: Accepted

Solution code:
from collections import deque
from itertools import product


def bfs(S):
    x, y = S
    dist = [[10 ** 9] * w for _ in range(h)]
    dist[y][x] = 0
    que = deque([S])

    while len(que) > 0:
        x, y = que.popleft()
        near_a = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
        num = product([-2, -1, 0, 1, 2], repeat=2)
        near_b = [(x + dx, y + dy) for dx, dy in num]

        for i, j in near_a:
            if (0 <= i < w and 0 <= j < h and
                    dist[j][i] > dist[y][x] and s[j][i] == '.'):
                dist[j][i] = dist[y][x]
                que.appendleft((i, j))
        for i, j in near_b:
            if (0 <= i < w and 0 <= j < h and
                    dist[j][i] > dist[y][x] + 1 and s[j][i] == '.'):
                dist[j][i] = dist[y][x] + 1
                que.append((i, j))
    return dist


h, w = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
s = [input() for _ in range(h)]

ans = bfs((Cw - 1, Ch - 1))[Dh - 1][Dw - 1]
print(-1 if ans == 10 ** 9 else ans)

Submission status: Accepted

Solution code:
from collections import deque


def solve(H, W, Ch, Cw, Dh, Dw, maze):
    # 後の条件分岐を簡略化するためワープしても迷路外に出ないように壁で囲む
    walled_maze = ['##{}##'.format(row) for row in maze]
    walled_maze.insert(0, '##{}##'.format('#' * W))
    walled_maze.insert(0, '##{}##'.format('#' * W))
    walled_maze.append('##{}##'.format('#' * W))
    walled_maze.append('##{}##'.format('#' * W))

    INF = 10 ** 12
    path = [[INF] * (W + 4) for _ in range(H + 4)]
    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]

    yet = deque()
    yet.append((Ch + 2, Cw + 2, 0))    # 囲った壁の分だけプラス
    path[Ch + 2][Cw + 2] = 0
    done = deque()

    while yet:
        y, x, s = yet.popleft()
        done.append((y, x, s))
        for dy, dx in walk:
            ny = y + dy
            nx = x + dx
            if walled_maze[ny][nx] == '.' and path[ny][nx] > s:
                path[ny][nx] = s
                yet.append((ny, nx, s))
        if len(yet) == 0:
            while done:
                y, x, s = done.popleft()
                for dy, dx in warp:
                    ny = y + dy
                    nx = x + dx
                    if walled_maze[ny][nx] == '.' and path[ny][nx] > s + 1:
                        path[ny][nx] = s + 1
                        yet.append((ny, nx, s + 1))
    ans = path[Dh + 2][Dw + 2] if path[Dh + 2][Dw + 2] < INF else -1
    print(ans)


if __name__ == '__main__':
    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)]
    solve(H, W, Ch, Cw, Dh, Dw, maze)

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())


def main():
    from collections import deque
    H, W = MI()
    C = LI()
    D = LI()
    C = [i - 1 for i in C]
    D = [i - 1 for i in D]
    S_ = []
    for i in range(H):
        s = S()
        S_.append(s)
    cost = [[10 ** 10] * W for _ in range(H)]
    cost[C[0]][C[1]] = 0
    queue = deque()
    queue.append(C)
    while len(queue) != 0:
        a = queue.popleft()
        a_cost = cost[a[0]][a[1]]
        for i in range(-2, 3):
            if a[0] + i < 0 or a[0] + i >= H:
                continue
            for j in range(-2, 3):
                if a[1] + j < 0 or a[1] + j >= W:
                    continue
                if i == j == 0:
                    continue
                b = [a[0] + i, a[1] + j]
                b_cost = cost[b[0]][b[1]]
                if S_[b[0]][b[1]] == '#':
                    continue
                if (abs(i) == 1 and j == 0) or (abs(j) == 1 and i == 0):
                    if a_cost < b_cost:
                        cost[b[0]][b[1]] = a_cost
                        queue.appendleft(b)
                else:
                    if a_cost + 1 < b_cost:
                        cost[b[0]][b[1]] = a_cost + 1
                        queue.append(b)
    ans = cost[D[0]][D[1]]
    if ans != 10 ** 10:
        print(ans)
    else:
        print(-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque


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


dh = [0, 0, 1, -1]
dw = [1, -1, 0, 0]
INF = float('inf')


def main():
    dist = [[INF] * W for i in range(H)]
    que = deque()
    dist[Ch][Cw] = 0
    que.append([Ch, Cw])

    # 01-BFS
    while que:
        h, w = que.popleft()
        d = dist[h][w]
        for i in range(4):
            nh = h + dh[i]
            nw = w + dw[i]
            if nh < 0 or nw < 0 or nh >= H or nw >= W:
                continue
            if S[nh][nw] == '#':
                continue
            if dist[nh][nw] <= d:
                continue
            dist[nh][nw] = d
            que.appendleft([nh, nw])
        
        # 魔法
        for mh in range(-2, 3):
            for mw in range(-2, 3):
                nh = h + mh
                nw = w + mw
                if nh < 0 or nw < 0 or nh >= H or nw >= W:
                    continue
                if S[nh][nw] == '#':
                    continue
                if dist[nh][nw] <= d + 1:
                    continue
                dist[nh][nw] = d + 1
                que.append([nh, nw])
    
    ans = dist[Dh][Dw]
    if ans == INF:
        ans = -1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import copy
from collections import deque

sys.setrecursionlimit(10**6)
input = sys.stdin.readline
#read = sys.stdin.buffer.read

digtmp = [(0, 1), (1, 0), (0, -1), (-1, 0)]
area = [
    (-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2),
    (-1, -2), (-1, -1), (-1, 0), (-1, 1), (-1, 2),
    (0, -2), (0, -1), (0, 1), (0, 2),
    (1, -2), (1, -1), (1, 0), (1, 1), (1, 2),
    (2, -2), (2, -1), (2, 0), (2, 1), (2, 2)
]

def warp(a:int, b:int, cnt:int):
    ans = []
    for i, j in area:
        x, y = a+i, b+j
        if 0 <= x < H and 0 <= y < W:
            if field[x][y] == '.' and check[x][y] == -1:
                check[x][y] = cnt
                ans.append((x, y))
    return ans


def main():
    global field, check, H, W
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())

    field = []
    check = [[-1] * W for _ in range(H)] 
    for h in range(H):
        tmp = list(input()[:-1])
        field.append(tmp)
    
    
    cnt = 0
    que = deque([(Ch-1, Cw-1)])
    for i in range(H*W):
        # BFS
        magic = []
        for _ in range(H*W):
            if len(que) == 0:
                break
            a, b = que.popleft()
            magic.append((a, b))
            for dx, dy in digtmp:
                x = a + dx
                y = b + dy
                if not (0 <= x < H and 0 <= y < W):
                    continue
                if check[x][y] != -1 or field[x][y] == '#':
                    continue
                check[x][y] = cnt
                que.append((x, y))

        # magic
        quetmp = []
        cnt += 1
        for _ in range(H*W):
            a, b = magic.pop()
            tmp = warp(a, b, cnt)
            quetmp += tmp 
            if len(magic) == 0:
                break
        que = deque(quetmp)
        
        if check[Dh-1][Dw-1] != -1:
            print(check[Dh-1][Dw-1])
            return
        if len(que) == 0:
            print(check[Dh-1][Dw-1])
            return


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int,input().split())
sh, sw = map(int,input().split())
gh, gw = map(int,input().split())
sh, sw, gh, gw = sh-1, sw-1, gh-1, gw-1
S = [input() for _ in range(H)]

INF = 10**9
ans = [[INF] * W for _ in range(H)]
ans[sh][sw] = 0

Q = deque([[sh,sw]])
while Q:
    h, w = Q.popleft()

    for nh, nw in [[h,w+1],[h,w-1],[h+1,w],[h-1,w]]:
        if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == "." and ans[nh][nw] > ans[h][w]:
            ans[nh][nw] = ans[h][w]
            Q.appendleft([nh, nw])

    for nh in range(h-2,h+3):
        for nw in range(w-2,w+3):
            if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == "." and ans[nh][nw] > ans[h][w] + 1:
                ans[nh][nw] = ans[h][w] + 1
                Q.append([nh,nw])

if ans[gh][gw] == INF:
    print(-1)
else:
    print(ans[gh][gw])

Submission status: Accepted

Solution code:
from collections import deque

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

c = [[] for i in range(h)]

for i in range(h):
    c[i] = input()
    
d = [[10000000 for i in range(w)] for j in range(h)]
    
d[ch-1][cw-1] = 0
que = deque([[ch-1,cw-1]])

dx = [1,0,-1,0]
dy = [0,1,0,-1]
ddx = [1,1,-1,-1,2,2,2,2,2,1,1,0,0,-1,-1,-2,-2,-2,-2,-2]
ddy = [1,-1,1,-1,2,1,0,-1,-2,2,-2,2,-2,2,-2,2,1,0,-1,-2]
    
while que:
    y,x = que.popleft()
        
    for k in range(4):
        nx = x + dx[k]
        ny = y + dy[k]
            
        if 0<=nx and nx<w and 0<=ny and ny<h and c[ny][nx] != '#':
            if d[ny][nx] > d[y][x]:
                d[ny][nx] = d[y][x]
                que.appendleft([ny,nx])
                
    for k in range(20):
        nx = x + ddx[k]
        ny = y + ddy[k]
            
        if 0<=nx and nx<w and 0<=ny and ny<h and c[ny][nx] != '#':
            if d[ny][nx] > d[y][x] + 1:
                d[ny][nx] = d[y][x] + 1
                que.append([ny,nx])

                
if d[dh-1][dw-1] == 10000000:
    print(-1)
else:
    print(d[dh-1][dw-1])

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
ch, cw = [int(i) - 1 for i in  input().split()]
dh, dw = [int(i) - 1 for i in  input().split()]
maze = []
for _ in range(H):
    a = input()
    maze.append(a)
d = deque([(ch, cw, 0)])
value = [[-1 for _ in range(W)] for _ in range(H)]
while d:
    h, w, v = d.popleft()
    if value[h][w] == -1:
        value[h][w] = v
        for hi in range(-2, 3):
            for wi in range(-2, 3):
                next_h = h + hi
                next_w = w + wi
                if (0 <= next_h < H) & (0 <= next_w < W):                
                    if (maze[next_h][next_w] == '.'):
                        if (abs(hi) + abs(wi) == 1) & (value[next_h][next_w] == -1):
                            d.appendleft((next_h, next_w, v))
                        elif (abs(hi) + abs(wi) > 1) & (value[next_h][next_w] == -1):
                            d.append((next_h, next_w, v + 1))
    else:
        continue
print(value[dh][dw])