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:
from collections import deque
h,w = map(int, input().split())
c = tuple(map(int, input().split()))
d = tuple(map(int, input().split()))
m = ['#' for _ in range(h+2)]
m[0] += '#'*w
m[h+1] += '#'*w
que = deque()
que.append(c)
warp = [[10**6 for _ in range(w+1)] for _ in range(h+1)]
for i in range(1,h+1):  m[i] += input()+'#'
up = lambda x,y: 1 if 0<x-1 and m[x-1][y]=='.' else 0
down = lambda x,y: 1 if x+1<=h and m[x+1][y]=='.' else 0
right = lambda x,y: 1 if y+1<=w and m[x][y+1]=='.' else 0
left = lambda x,y: 1 if 0<y-1 and m[x][y-1]=='.' else 0

def jump(x,y,cost):
  deq = deque()
  for i in range(x-2,x+3):
    if i<=0 or h<i:  continue
    for j in range(y-2,y+3):
      if j<=0 or w<j:  continue
      if m[i][j] == '.' and warp[i][j]>cost+1:
        warp[i][j] = cost+1
        deq.append((i,j))
  return deq
  
warp[c[0]][c[1]] = 0
while que:
  q = que.popleft()
  row = q[0]
  col = q[1]
  cost = warp[row][col]
  if up(row,col) and warp[row-1][col]>cost:
    que.appendleft((row-1,col))
    warp[row-1][col] = cost
  if down(row,col) and warp[row+1][col]>cost:
    que.appendleft((row+1,col))
    warp[row+1][col] = cost
  if right(row,col) and warp[row][col+1]>cost:
    que.appendleft((row,col+1))
    warp[row][col+1] = cost
  if left(row,col) and warp[row][col-1]>cost:
    que.appendleft((row,col-1))
    warp[row][col-1] = cost
  que.extend(jump(row,col,cost))

if warp[d[0]][d[1]] != 10**6:  print(warp[d[0]][d[1]])
else:  print(-1)

Submission status: Accepted

Solution code:
from collections import deque
number=list(map(int,input().split()))
H,W=number[0],number[1]
C=list(map(int,input().split()))
D=list(map(int,input().split()))
S=[str(input()) for i in range(H)]

INF=10**9
dp=[[INF]*W for i in range(H)]
trans_a=[(1,0),(0,1),(-1,0),(0,-1)]
trans_b=[(i,j) for i in range(-2,3) for j in range(-2,3) if (i,j) not in [(0,0)]+trans_a]
Q=deque()
t=0
C.append(t)
Q.append((C[0]-1,C[1]-1,C[2]))
dp[C[0]-1][C[1]-1]=t

while Q:
    x,y,t=Q[0][0],Q[0][1],Q[0][2]
    Q.popleft()
    for dx,dy in trans_a:
        nx=x+dx
        ny=y+dy
        if 0<=nx<H and 0<=ny<W and S[nx][ny]!="#" and dp[nx][ny]>t:
            dp[nx][ny]=t
            Q.appendleft((nx,ny,t))
    
    for dx,dy in trans_b:
        nx=x+dx
        ny=y+dy
        if 0<=nx<H and 0<=ny<W and S[nx][ny]!="#" and dp[nx][ny]>t+1:
            dp[nx][ny]=t+1
            Q.append((nx,ny,t+1))

if dp[D[0]-1][D[1]-1]==INF:
    print(-1)

else:
    print(dp[D[0]-1][D[1]-1])

Submission status: Accepted

Solution code:
from collections import deque

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

dh = [-1, 0, 0, 1]
dw = [0, 1, -1, 0]

INF = pow(10, 10)
seen = [[INF] * W for _ in range(H)]
seen[Ch][Cw] = 0
q = deque()
q.append([Ch, Cw])

while q:
    th, tw = q.pop()
    for i in range(4):
        nh = th + dh[i]
        nw = tw + dw[i]
        if nh < 0 or nh > H - 1 or nw < 0 or nw > W - 1:
            continue
        if S[nh][nw] == '#':
            continue
        if seen[nh][nw] <= seen[th][tw]:
            continue
        seen[nh][nw] = seen[th][tw]
        q.append([nh, nw])
    for dh2 in range(-2, 3):
        for dw2 in range(-2, 3):
            if dh2 == 0 and dw2 == 0:
                continue
            nh = th + dh2
            nw = tw + dw2
            if nh < 0 or nh > H - 1 or nw < 0 or nw > W - 1:
                continue
            if S[nh][nw] == '#':
                continue
            if seen[nh][nw] <= seen[th][tw] + 1:
                continue
            seen[nh][nw] = seen[th][tw] + 1
            q.appendleft([nh, nw])

if seen[Dh][Dw] is INF:
    print(-1)
else:
    print(seen[Dh][Dw])

Submission status: Accepted

Solution code:
from collections import deque

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

dh = [-1, 0, 0, 1]
dw = [0, 1, -1, 0]

INF = pow(10, 10)
seen = [[INF] * W for _ in range(H)]
seen[Ch][Cw] = 0
q = deque()
q.append([Ch, Cw])

while q:
    th, tw = q.pop()
    for i in range(4):
        nh = th + dh[i]
        nw = tw + dw[i]
        if nh < 0 or nh > H - 1 or nw < 0 or nw > W - 1 or S[nh][nw] == '#' or seen[nh][nw] <= seen[th][tw]:
            continue
        seen[nh][nw] = seen[th][tw]
        q.append([nh, nw])
    for dh2 in range(-2, 3):
        for dw2 in range(-2, 3):
            if dh2 == 0 and dw2 == 0:
                continue
            nh = th + dh2
            nw = tw + dw2
            if nh < 0 or nh > H - 1 or nw < 0 or nw > W - 1 or S[nh][nw] == '#' or seen[nh][nw] <= seen[th][tw] + 1:
                continue
            seen[nh][nw] = seen[th][tw] + 1
            q.appendleft([nh, nw])

if seen[Dh][Dw] is INF:
    print(-1)
else:
    print(seen[Dh][Dw])

Submission status: Accepted

Solution code:
INF = 10**9
from heapq import heappop,heappush
H,W = (int(i) for i in input().split())
Ch,Cw = (int(i)-1 for i in input().split())
Dh,Dw = (int(i)-1 for i in input().split())
S = [input() for i in range(H)]

dist = [[INF]*W for _ in range(H)]
dist[Ch][Cw]= 0
que = [(0,Ch*W+Cw)]
while(que):
    u_dist,u = heappop(que)
    uh,uw = u//W,u%W
    #if dist[uh][uw] < u_dist:
    #    continue
    for dh in range(-2,3):
        for dw in range(-2,3):
            nh = uh + dh
            nw = uw + dw
            if nh<0 or H <= nh or nw < 0 or W <= nw:
                continue
            if S[nh][nw]=="#":
                continue
            cost = 0 if abs(dh)+abs(dw)<=1 else 1
            if dist[nh][nw] > dist[uh][uw] + cost:
                dist[nh][nw] = dist[uh][uw] + cost
                heappush(que,(dist[nh][nw],nh*W+nw))
if dist[Dh][Dw] == INF:
    print(-1)
else:
    print(dist[Dh][Dw])

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
from collections import *
l=[(0,1),(0,-1),(1,0),(-1,0)]
dp=[[float("inf")]*w for i in range(h)]
f=[[False]*w for i in range (h)]
ch,cw=map(int,input().split())
sx,sy=ch-1,cw-1
dh,dw=map(int,input().split())
gx,gy=dh-1,dw-1
for i in range(h):
    s=input()
    for j in range(w):
        if s[j]==".":
            f[i][j]=True
q=deque()
q.append((sx,sy))
dp[sx][sy]=0
while q:
    x,y=q.popleft()
    for a,b in l:
        nx,ny=x+a,y+b
        if 0<=nx<h and 0<=ny<w:
            if f[nx][ny]==True and dp[nx][ny]>dp[x][y]:
                dp[nx][ny]=dp[x][y]
                q.appendleft((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:
                if f[nx][ny]==True and dp[nx][ny]>dp[x][y]+1:
                    dp[nx][ny]=dp[x][y]+1
                    q.append((nx,ny))
if dp[gx][gy]==float("inf"):
    print(-1)
else:
    print(dp[gx][gy])

Submission status: Accepted

Solution code:
#atcoder template
def main():
    import sys
    imput = sys.stdin.readline
    #文字列入力の時は上記はerrorとなる。
    #ここにコード
    #input
    h, w = map(int, input().split())
    c_h, c_w = map(int, input().split())
    d_h, d_w = map(int, input().split())
    s = [input() for _ in range(h)]

    #output
    from collections import deque

    INF = pow(10, 10)
    dp = [[INF] * w for _ in range(h)]

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

    q = deque([])
    q.append((c_h-1, c_w-1, 0))
    dp[c_h-1][c_w-1] = 0

    while q:
        x, y, t = q.popleft()

        for dx, dy in trans_a:
            nx, ny = x + dx, y + dy
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and dp[nx][ny] > t:
                q.appendleft((nx, ny, t))#ここを変更
                dp[nx][ny] = t#ここを変更

        for dx, dy in trans_b:
            nx, ny = x + dx, y + dy
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and dp[nx][ny] > t + 1:
                q.append((nx, ny, t+1))
                dp[nx][ny] = t + 1

    answer = dp[d_h-1][d_w-1]

    # %%
    if answer == INF:
        print(-1)
    else:
        print(answer)

    #N = 1のときなどcorner caseを確認！
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from heapq import heappush,heappop
from collections import deque
h,w=map(int,input().split())
sx,sy=map(int,input().split())
sx-=1
sy-=1
gx,gy=map(int,input().split())
gx-=1
gy-=1
g=[list(input()) for _ in range(h)]
v=[[0 for j in range(w)] for i in range(h)]
v2=[[0 for j in range(w)] for i in range(h)]
q=deque([])
q.append([0,sx+h*sy])
while q:
    c,xy=q.popleft()
    x=xy%h
    y=xy//h
    if x==gx and y==gy:
        print(c)
        exit()
    if v[x][y]==1:
        continue
    v[x][y]=1
    for a in range(-2,3):
        for b in range(-2,3):
            if a==b==0:
                continue
            if a*b==0 and abs(a+b)==1:
                nx=x+a
                ny=y+b
                if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and v[nx][ny]==0:
                    q.appendleft([c,nx+h*ny])
                continue
            nx=x+a
            ny=y+b
            if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and v[nx][ny]==0 and v2[nx][ny]==0:
                q.append([c+1,nx+h*ny])
                v2[nx][ny]=1
print(-1)

Submission status: Accepted

Solution code:
from heapq import heappush,heappop
from collections import deque
h,w=map(int,input().split())
sx,sy=map(int,input().split())
sx-=1
sy-=1
gx,gy=map(int,input().split())
gx-=1
gy-=1
g=[list(input()) for _ in range(h)]
v=[[0 for j in range(w)] for i in range(h)]
v2=[[0 for j in range(w)] for i in range(h)]
q=deque([])
q.append([0,sx,sy])
while q:
    c,x,y=q.popleft()
    if x==gx and y==gy:
        print(c)
        exit()
    if v[x][y]==1:
        continue
    v[x][y]=1
    for a in range(-2,3):
        for b in range(-2,3):
            if a==b==0:
                continue
            if a*b==0 and abs(a+b)==1:
                nx=x+a
                ny=y+b
                if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and v[nx][ny]==0:
                    q.appendleft([c,nx,ny])
                continue
            nx=x+a
            ny=y+b
            if 0<=nx<h and 0<=ny<w and g[nx][ny]=='.' and v[nx][ny]==0 and v2[nx][ny]==0:
                q.append([c+1,nx,ny])
                v2[nx][ny]=1
print(-1)

Submission status: Accepted

Solution code:
from heapq import heappush,heappop,heapify
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 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

mo=10**9+7
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))
import sys
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

inf=1<<20
def dijkstra(edge,st):
    n=len(edge)
    d=[(0 if st==i else inf) for i in range(n)]
    q=[(0,st)]
    heapify(q)
    v=[False]*n
    while q:
        dist,cur=heappop(q)
        if v[cur]:
            continue
        v[cur]=True
        for dst,dist in edge[cur]:
            alt=d[cur]+dist
            if alt<d[dst]:
                d[dst]=alt
                heappush(q,(alt,dst))
    return d


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


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]
nbw=[2,2*w+1,2*w+2,w+1,w+2,+2*w,2*w-1,2*w-2,w-1,w-2]
nb=[1,-1,w,-w]
nb=[1,w]
d=[-1]*n
g=[[]for i in range(n)]
for i in range(n):
    if m[i]==1:
      continue
    for di in nbw:
        nx=i+di
        if 0<=nx<n and m[nx]!=1:
            g[i]+=(nx,1),
            g[nx]+=(i,1),
    for di in nb:
        nx=i+di
        if 0<=nx<n and m[nx]!=1:
            g[i]+=(nx,0),
            g[nx]+=(i,0),
            
d=dijkstra(g,sh*w+sw)
ans=d[gh*w+gw]
if ans==inf:
    ans=-1
print(ans)

Submission status: Accepted

Solution code:
from heapq import heappush,heappop,heapify
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 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

mo=10**9+7
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))
import sys
read=sys.stdin.buffer.read;readline=sys.stdin.buffer.readline;input=lambda:sys.stdin.readline().rstrip()

inf=1<<20
def dijkstra(edge,st):
    n=len(edge)
    d=[(0 if st==i else inf) for i in range(n)]
    q=[(0,st)]
    heapify(q)
    v=[False]*n
    while q:
        dist,cur=heappop(q)
        if v[cur]:
            continue
        v[cur]=True
        for x in edge[cur]:
            dst,dist=x>>1,x%2
            alt=d[cur]+dist
            if alt<d[dst]:
                d[dst]=alt
                heappush(q,(alt,dst))
    return d


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


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]
nbw=[2,2*w+1,2*w+2,w+1,w+2,+2*w,2*w-1,2*w-2,w-1,w-2]
nb=[1,-1,w,-w]
nb=[1,w]
d=[-1]*n
g=[[]for i in range(n)]
for i in range(n):
    if m[i]==1:
      continue
    for di in nbw:
        nx=i+di
        if 0<=nx<n and m[nx]!=1:
            g[i]+=(nx*2+1),
            g[nx]+=(i*2+1),
    for di in nb:
        nx=i+di
        if 0<=nx<n and m[nx]!=1:
            g[i]+=(nx*2),
            g[nx]+=(i*2),
            
d=dijkstra(g,sh*w+sw)
ans=d[gh*w+gw]
if ans==inf:
    ans=-1
print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
sh, sw = map(int, input().split())
gh, gw = map(int, input().split())

sh += 1
sw += 1
gh += 1
gw += 1
s = sh*3000+sw
g = gh*3000+gw

S = [0]*(H+4)
S[0] = '*'*(W+4)
S[1] = '*'*(W+4)
S[-2] = '*'*(W+4)
S[-1] = '*'*(W+4)
for h in range(2,H+2):
  S[h] = '**' + input() + '**'

visited = [[float('inf')]*(W+4) for _ in range(H+4)]
dh1 = [0,1,0,-1]
dw1 = [1,0,-1,0]
dh2 = [2,2,2,2,2,1,1,1,1,0,0,-1,-1,-1,-1,-2,-2,-2,-2,-2]
dw2 = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
d = []
heapify(d)
heappush(d,s)
ans = float('inf')
while len(d)>0:
  a = heappop(d)
  cnt,a1 = divmod(a,10**7)
  h,w = divmod(a1,3000)
  if cnt>=ans:
    break
  visited[h][w] = cnt
  for i in range(4):
    h1 = h+dh1[i]
    w1 = w+dw1[i]
    if (h1,w1)==(gh,gw):
      ans = cnt
    if S[h1][w1]=='.':
      if visited[h1][w1]>cnt:
        visited[h1][w1]=cnt
        heappush(d,cnt*(10**7)+h1*3000+w1)
  for i in range(20):
    h2 = h+dh2[i]
    w2 = w+dw2[i]
    if (h2,w2)==(gh,gw):
      ans = cnt+1
    if S[h2][w2]=='.':
      if visited[h2][w2]>cnt+1:
        visited[h2][w2]=cnt+1
        heappush(d,(cnt+1)*(10**7)+h2*3000+w2)
ans = ans if ans<float('inf') else -1
print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
sh, sw = map(int, input().split())
gh, gw = map(int, input().split())

sh += 1
sw += 1
gh += 1
gw += 1

S = [0]*(H+4)
S[0] = '*'*(W+4)
S[1] = '*'*(W+4)
S[-2] = '*'*(W+4)
S[-1] = '*'*(W+4)
for h in range(2,H+2):
  S[h] = '**' + input() + '**'

visited = [[float('inf')]*(W+4) for _ in range(H+4)]
dh1 = [0,1,0,-1]
dw1 = [1,0,-1,0]
dh2 = [2,2,2,2,2,1,1,1,1,0,0,-1,-1,-1,-1,-2,-2,-2,-2,-2]
dw2 = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
d = []
heapify(d)
heappush(d,(0,sh,sw))
ans = float('inf')
while len(d)>0:
  cnt,h,w = heappop(d)
  if cnt>=ans:
    break
  visited[h][w] = cnt
  for i in range(4):
    h1 = h+dh1[i]
    w1 = w+dw1[i]
    if (h1,w1)==(gh,gw):
      ans = cnt
    if S[h1][w1]=='.':
      if visited[h1][w1]>cnt:
        visited[h1][w1]=cnt
        heappush(d,(cnt,h1,w1))
  for i in range(20):
    h2 = h+dh2[i]
    w2 = w+dw2[i]
    if (h2,w2)==(gh,gw):
      ans = cnt+1
    if S[h2][w2]=='.':
      if visited[h2][w2]>cnt+1:
        visited[h2][w2]=cnt+1
        heappush(d,(cnt+1,h2,w2))
ans = ans if ans<float('inf') else -1
print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
sh, sw = map(int, input().split())
gh, gw = map(int, input().split())

sh += 1
sw += 1
gh += 1
gw += 1

S = [0]*(H+4)
S[0] = '*'*(W+4)
S[1] = '*'*(W+4)
S[-2] = '*'*(W+4)
S[-1] = '*'*(W+4)
for h in range(2,H+2):
  S[h] = '**' + input() + '**'

visited = [[float('inf')]*(W+4) for _ in range(H+4)]
dh1 = [0,1,0,-1]
dw1 = [1,0,-1,0]
dh2 = [2,2,2,2,2,1,1,1,1,0,0,-1,-1,-1,-1,-2,-2,-2,-2,-2]
dw2 = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
d = []
heapify(d)
heappush(d,(0,sh,sw))
ans = float('inf')
while len(d)>0:
  cnt,h,w = heappop(d)
  if cnt>=ans:
    break
  visited[h][w] = cnt
  for i in range(4):
    h1 = h+dh1[i]
    w1 = w+dw1[i]
    if (h1,w1)==(gh,gw):
      ans = min(ans,cnt)
    if S[h1][w1]=='.':
      if visited[h1][w1]>cnt:
        visited[h1][w1]=cnt
        heappush(d,(cnt,h1,w1))
  for i in range(20):
    h2 = h+dh2[i]
    w2 = w+dw2[i]
    if (h2,w2)==(gh,gw):
      ans = min(ans,cnt+1)
    if S[h2][w2]=='.':
      if visited[h2][w2]>cnt+1:
        visited[h2][w2]=cnt+1
        heappush(d,(cnt+1,h2,w2))
ans = ans if ans<float('inf') else -1
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
def bfs():
    move=[[1,0],[0,1],[-1,0],[0,-1]]
    
    queue=deque()
    queue.append([sy,sx]) #queue=deque([[sy,sx]])でもよい
    visited[sy][sx]=0 #スタート地点の距離は0
    while queue:
        y,x=queue.popleft()
        cnt=visited[y][x]
        
        for dy,dx in move:
            my,mx=y+dy,x+dx 
            if my<0 or my>=tate:
                continue
            if mx<0 or mx>=yoko:
                continue
            if maze[my][mx]=="#":
                continue
            if visited[my][mx]>cnt:
                queue.appendleft([my,mx])
                visited[my][mx]=cnt # visitedは距離も兼ねてる
        for my in range(y-2,y+3):
            for mx in range(x-2,x+3):
                if my<0 or my>=tate:
                    continue
                if mx<0 or mx>=yoko:
                    continue
                if maze[my][mx]=="#":
                    continue
                if visited[my][mx]>cnt+1:
                    queue.append([my,mx])
                    visited[my][mx]=cnt+1
    if visited[gy][gx]==inf:
        print(-1)
    else:
        print(visited[gy][gx])


tate,yoko=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
sy,sx,gy,gx=sy-1,sx-1,gy-1,gx-1
maze=[]
inf=float('inf')
visited=[[inf]*yoko for i in range(tate)]

for i in range(tate):
    line=list(input())
    maze.append(line)
bfs()

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)])
    near = list(product(range(-2, 3), repeat=2))

    while len(que) > 0:
        x, y = que.popleft()
        if (x, y) == (Dw - 1, Dh - 1):
            return dist[y][x]

        for dx, dy in near:
            cnt = (abs(dx) + abs(dy) >= 2)
            i, j = x + dx, y + dy
            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:
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)])
    near = list(product(range(-2, 3), repeat=2))

    while len(que) > 0:
        x, y = que.popleft()
        if (x, y) == (Dw - 1, Dh - 1):
            return dist[y][x]

        for dx, dy in near:
            cnt = (abs(dx) + abs(dy) >= 2)
            i, j = x + dx, y + dy
            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))
    else:
        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:
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)])
    near = product(range(-2, 3), repeat=2)

    while len(que) > 0:
        x, y = que.popleft()
        if (x, y) == (Dw - 1, Dh - 1):
            return dist[y][x]

        for dx, dy in product(range(-2, 3), repeat=2):
            cnt = (abs(dx) + abs(dy) >= 2)
            i, j = x + dx, y + dy
            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))
    else:
        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:
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, dist[y][x])])

    while len(que) > 0:
        x, y, d = que.popleft()
        if (x, y) == (Dw - 1, Dh - 1):
            return dist[y][x]

        for i, j in product(range(-2, 3), repeat=2):
            cnt = (abs(i) + abs(j) >= 2)
            i, j = x + i, y + j
            if (0 <= i < w and 0 <= j < h and
                    dist[j][i] > d + cnt and s[j][i] == '.'):
                dist[j][i] = d + cnt
                if cnt == 0:
                    que.appendleft((i, j, d + cnt))
                elif cnt == 1:
                    que.append((i, j, d+cnt))
    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:
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()
        num = product([-2, -1, 0, 1, 2], repeat=2)
        near = [(x + dx, y + dy) for dx, dy in num]
        if (x, y) == (Dw - 1, Dh - 1):
            return dist[y][x]

        for i, j in near:
            cnt = (abs(x - i) + abs(y - j) >= 2)
            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))