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())
cy, cx = map(int, input().split())
sy, sx = map(int, input().split())
tiles = [list(input()) for _ in range(H)]

# initialization
INF = 10**4
arrived = [[INF for _ in range(W)] for __ in range(H)]
paths = deque()
warps = deque()
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]
moves = [-2, -1, 0, 1, 2]
arrived[cy-1][cx-1] = 0
paths.append([cx-1, cy-1])
count = 0

# BFS
while(len(paths) > 0):
  while(len(paths) > 0):
    nx, ny = paths.popleft()
    for i in range(4):
      if 0 <= nx+dx[i] < W and 0 <= ny+dy[i] < H and arrived[ny+dy[i]][nx+dx[i]] > count and tiles[ny+dy[i]][nx+dx[i]] == '.':
        paths.append([nx+dx[i], ny+dy[i]])
        arrived[ny+dy[i]][nx+dx[i]] = count
    for x in moves:
      for y in moves:
        if 0 <= nx+x < W and 0 <= ny+y < H and arrived[ny+y][nx+x] == INF and tiles[ny+y][nx+x] == '.':
          warps.append([nx+x, ny+y])
  count += 1
  while(len(warps) > 0):
    nx, ny = warps.popleft()
    if arrived[ny][nx] == INF:
      arrived[ny][nx] = count
      paths.append([nx, ny])

if arrived[sy-1][sx-1] != INF:
  print(arrived[sy-1][sx-1])
else:
  print(-1)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

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

from collections import deque
dq = deque([(sh, sw)])
while dq:
    h, w = dq.popleft()
    for dh in range(-2, 3):
        for dw in range(-2, 3): # [dh,dw]:[-2,-2]~[2,2]
            nh = h + dh; nw = w + dw
            if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.':
                f = dh*dh + dw*dw # 上下左右か否か
                if f == 1 and dst[nh][nw] > dst[h][w]:
                    dst[nh][nw] = dst[h][w]
                    dq.appendleft((nh, nw))
                elif f > 1 and dst[nh][nw] > dst[h][w] + 1:
                    dst[nh][nw] = dst[h][w] + 1
                    dq.append((nh, nw))

print(-1 if dst[eh][ew]==INF else dst[eh][ew])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

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

from collections import deque
dq = deque([(sh, sw)])
while dq:
    h, w = dq.popleft()

    for dh in range(-2, 3):
        for dw in range(-2, 3): # [dh,dw]:[-2,-2]~[2,2]
            nh = h + dh; nw = w + dw
            if dh*dh + dw*dw == 1:
                if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and dst[h][w] < dst[nh][nw]:
                    dst[nh][nw] = dst[h][w]
                    dq.appendleft((nh, nw))
            elif dh*dh + dw*dw > 1:
                if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and dst[h][w] + 1 < dst[nh][nw]:
                    dst[nh][nw] = dst[h][w] + 1
                    dq.append((nh, nw))

print(-1 if dst[eh][ew]==INF else dst[eh][ew])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()
    if 0 <= h < H and 0 <= w < W and dst[h][w] < 0 and S[h][w] != '#':
        dst[h][w] = d
        for dh in range(-2, 3):
            for dw in range(-2, 3): # [dh,dw]:[-2,-2]~[2,2]
                if dh*dh + dw*dw == 1: dq.appendleft((h + dh, w + dw, d))
                elif dh*dh + dw*dw > 1: dq.append((h + dh, w + dw, d+1))

print(dst[eh][ew])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()
    if 0 <= h < H and 0 <= w < W and dst[h][w] < 0 and S[h][w] != '#':
        dst[h][w] = d
        for dh in range(-2, 3):
            for dw in range(-2, 3): # [dh,dw]:[-2,-2]~[2,2]
                if dh*dh + dw*dw < 1: continue
                if dh*dh + dw*dw > 1: dq.append((h + dh, w + dw, d+1))
                else: dq.appendleft((h + dh, w + dw, d))

print(dst[eh][ew])

Submission status: Accepted

Solution code:
h,w = map(int, input().split())

sy, sx = map(int, input().split())
sy -= 1
sx -= 1
gy, gx = map(int, input().split())
gy -= 1
gx -= 1

s = [[""] for _ in range(h)]
for i in range(h):
    s[i] = input()

from collections import deque
d = deque()

visited = [[False]*w for _ in range(h)]

d.append([sy,sx,0])

while len(d) > 0:
    y,x,c = d.popleft()
    
    if visited[y][x] is True:
        continue
    else:
        visited[y][x] = True
    
    if gy == y and gx == x:
        print(c)
        exit(0)

    dxy = [[1,0], [-1, 0], [0, 1], [0, -1]]
    for dx, dy in dxy:
        nx = dx + x
        ny = dy + y
        if nx < 0 or nx >= w or ny < 0 or ny >= h:
            continue
        if s[ny][nx] == "#":
            continue
        if visited[ny][nx] is True:
            continue
        d.appendleft([ny, nx, c])

    for dy in range(-2, 3):
        for dx in range(-2, 3):
            nx = dx + x
            ny = dy + y
            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue
            if s[ny][nx] == "#":
                continue
            if visited[ny][nx] is True:
                continue
            d.append([ny, nx, c+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

for _ in range(1):
    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:
H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
ch, cw, dh, dw = ch - 1, cw - 1, dh - 1, dw - 1
S = [input() for _ in range(H)]

from collections import deque

def is_valid(h, w):
    if 0 <= h < H and 0 <= w < W and S[h][w] == '.':
        return True
    else:
        return False

Dh = (1, 0, -1, 0)
Dw = (0, 1, 0, -1)

INF = float('inf')
dist = [[INF] * W for _ in range(H)]
dist[ch][cw] = 0
q = deque([(ch, cw)])

while q:
    ph, pw = q.popleft()
    for k in range(4):
        nh, nw = ph + Dh[k], pw + Dw[k]
        if is_valid(nh, nw):
            if dist[nh][nw] > dist[ph][pw]:
                dist[nh][nw] = dist[ph][pw]
                q.appendleft((nh, nw))
    for nh in range(ph - 2, ph + 3):
        for nw in range(pw - 2, pw + 3):
            if is_valid(nh, nw):
                if dist[nh][nw] > dist[ph][pw] + 1:
                   dist[nh][nw] = dist[ph][pw] + 1
                   q.append((nh, nw))

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

Submission status: Accepted

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

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

maze = []
for i in range(H):
    a = list(input())
    maze.append(a)

queue = deque([(ch, cw, 0)])

dist = [[float("inf") for _ in range(W)] for _ in range(H)]
dist[ch][cw] = 0

while queue:
    y, x, cnt= queue.popleft()

    for a, b in ([1, 0], [-1, 0], [0, 1], [0, -1]):
        new_y, new_x = y+a, x+b
        if 0 <= new_y < H and 0 <= new_x < W and maze[new_y][new_x] != '#':
            if dist[new_y][new_x] == float("inf") or dist[new_y][new_x] > cnt:
                queue.appendleft((new_y, new_x, cnt))
                dist[new_y][new_x] = cnt

    for a in range(-2, 3):
        for b in range(-2, 3):
            new_y, new_x = y + a, x + b
            if 0 <= new_y < H and 0 <= new_x < W and maze[new_y][new_x] != '#':
                if dist[new_y][new_x] == float("inf") or dist[new_y][new_x] > cnt + 1:
                    queue.append((new_y, new_x, cnt+1))
                    dist[new_y][new_x] = cnt + 1

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

Submission status: Accepted

Solution code:
from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict, Counter
from heapq import heappush, heappop
from functools import lru_cache
import math

#setrecursionlimit(10**6)
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())
rlf = lambda: map(float, stdin.readline().split())

INF, NINF = float('inf'), float('-inf')
MOD = 10**9 + 7

def main():
	rows, cols = rli()
	r0, c0 = rli(); r0 -= 1; c0 -= 1;
	r1, c1 = rli(); r1 -= 1; c1 -= 1;
	G = []
	for _ in range(rows):
		row = []
		for c in rll()[0]:
			if c == "#": 
				row.append(1)
			else:
				row.append(0)
		G.append(row)

	inside = lambda r, c: r>=0 and c>=0 and r<rows and c<cols	
	seen = [0 for _ in range(rows*cols+10)]
	Q = deque() #(num magics, r, c)
	Q.append((0, r0, c0))
	ans = INF
	while Q:
		magics, r, c = Q.pop()
		val = r*cols + c 
		if seen[val]: continue
		seen[val] = True
		if r == r1 and c == c1:
			ans = magics 
			break
		for dr in range(-2, 3):
			for dc in range(-2, 3):
				nr, nc = r + dr, c + dc 
				if not inside(nr, nc) or seen[cols*nr + nc] or G[nr][nc] == 1: continue
				if abs(dr) + abs(dc) > 1:
					Q.appendleft((magics+1, nr, nc))
				else:
					Q.append((magics, nr, nc))
	print(ans if ans < INF else -1)
	stdout.close()

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
from collections import deque

def solve():
    H,W = map(int,input().split())
    C = list(map(int,input().split()))
    D = list(map(int,input().split()))

    S = ["##" + input() + "##" for _ in range(H)]
    for i in range(2):
        S.insert(0,"#"*(W+4))
        S.append("#"*(W+4))

    INF = float("inf")
    cost = [[INF for _ in range(W+4)] for _ in range(H+4)]
    cost0 = deque()
    ans = -1

    cost0.append((C[0]+1, C[1]+1, 0))
    cost[C[0]+1][C[1]+1] = 0

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

    cost1 = deque()

    while cost0:
        h,w,c = cost0.popleft()
        cost1.append((h,w,c))

        for i, j in move:
            dh = h+i
            dw = w+j
            if S[dh][dw] == "." and c < cost[dh][dw]:
                cost[dh][dw] = c
                cost0.appendleft((dh, dw, cost[dh][dw]))
        
        if len(cost0) == 0:
            while cost1:
                h, w, c = cost1.popleft()
                for i, j in warp:
                    dh = h+i
                    dw = w+j
                    if S[dh][dw] == "." and c+1 < cost[dh][dw]:
                        cost[dh][dw] = c+1
                        cost0.append((dh,dw, cost[dh][dw]))
        
        if cost[D[0]+1][D[1]+1] != INF:
            ans = cost[D[0]+1][D[1]+1]

    print(ans)

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
from collections import deque

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

c=-1
for i in range(h):
    for j in range(w):
        if s[i][j]!='.':
            continue
        c+=1
        stk=[(i,j)]
        while stk:
            ii,jj=stk.pop()
            s[ii][jj]=c
            for di,dj in (-1,0),(0,1),(1,0),(0,-1):
                ni,nj=ii+di,jj+dj
                if not (0<=ni<h and 0<=nj<w):
                    continue
                if s[ni][nj]!='.':
                    continue
                stk.append((ni,nj))

n=c+1
cc=dc=-1
dirs=[-2,-1,0,1,2]
adj=[{*()} for _ in range(n)]
for i in range(h):
    for j in range(w):
        u=s[i][j]
        if u=='#':
            continue
        if i==ch and j==cw:
            cc=u
        elif i==dh and j==dw:
            dc=u
        for di in dirs:
            for dj in dirs:
                if di==dj==0:
                    continue
                ni,nj=i+di,j+dj
                if not (0<=ni<h and 0<=nj<w):
                    continue
                v=s[ni][nj]
                if v=='#':
                    continue
                if u!=v:
                    adj[u].add(v)
                    adj[v].add(u)

que=deque()                
que.append(cc)
vis={cc}
m=-1
while que:
    m+=1
    for _ in range(len(que)):
        u=que.popleft()
        if u==dc:
            print(m)
            exit()
        for v in adj[u]:
            if v in vis:
                continue
            vis.add(v)
            que.append(v)

print(-1)

Submission status: Accepted

Solution code:
#import numpy as np
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

maze = [input() for _ in range(H)]

INF = 10 ** 12

score = [[INF] * W for _ in range(H)]

score[Ch][Cw] = 0

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

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 candidates:
    h, w = candidates.popleft()
    # move
    for dh, dw in walk:
        y = h + dh
        x = w + dw
        s = score[h][w]
        if y < 0 or H <= y:
            continue
        if x < 0 or W <= x:
            continue        
        if maze[y][x] == '.' and score[y][x] > s:
            score[y][x] = s
            candidates.appendleft((y, x))
    # warp
    for dh, dw in warp:
        y = h + dh
        x = w + dw
        s = score[h][w]
        if y < 0 or H <= y:
            continue
        if x < 0 or W <= x:
            continue
        if maze[y][x] == '.' and score[y][x] > s + 1:
            score[y][x] = s + 1
            candidates.append((y, x))

if score[Dh][Dw] == INF:
    print(-1)
else:
    print (score[Dh][Dw])

Submission status: Accepted

Solution code:
from collections import deque
import sys

imput = sys.stdin.readline

h,w = map(int,input().split())
sy,sx= map(int,input().split())
gy,gx= map(int,input().split())
S=[]



for i in range(h):
    S.append(input())

walk = [[1,0],[-1,0],[0,1],[0,-1]]
move = [[x,y] for x in range(-2,3) for y in range(-2,3) if [x,y] not in walk + [[0,0]]] 

dist = [[9999999]*w for i in range(h)]
#visited = [[0]*w for i in range(h)]

q=deque()
q.append((sx-1,sy-1,0))
dist[sy-1][sx-1]=0
goaled = 0
endwarp=0
#while goaled==0:
while len(q):
    endwarp=0
    
    x,y,d = q.popleft()
    
#    if x==gx-1 and y==gy-1:
#        goaled=1
#        print(d)
#        break
    
#    print(x,y,d)
    for i in walk:
        if 0<=x+i[0]<w and 0<=y+i[1]<h and S[y+i[1]][x+i[0]]!="#" and dist[y+i[1]][x+i[0]] > d:

                    dist[y+i[1]][x+i[0]] = d
                    q.appendleft((x+i[0],y+i[1],d+0))

    for i in move:
        if 0<=x+i[0]<w and 0<=y+i[1]<h and S[y+i[1]][x+i[0]]!="#" and dist[y+i[1]][x+i[0]] > d+1:

                    dist[y+i[1]][x+i[0]] = d+1
                    q.append((x+i[0],y+i[1],d+1))
                        
                        
                         
    
    

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

Submission status: Accepted

Solution code:
import heapq
import numpy as np
from numba import njit,i8,b1

h,w = map(int,input().split())
sh,sw = map(int,input().split())
gh,gw = map(int,input().split())
s = np.array([list(input()) for _ in range(h)]) == "#"

@njit(i8(i8,i8,i8,i8,i8,i8,b1[:,:]))
def solve(h,w,sh,sw,gh,gw,s):

    sh-=1; sw-=1; gh-=1; gw-=1;

    INF = 10**7
    dist = [[INF]*w for _ in range(h)]
    dist[sh][sw] = 0
    q = [(0,sh,sw)]
    while q:

        d,vsh,vsw = heapq.heappop(q)

        for dh in range(-2,3):
            for dw in range(-2,3):
                newh = vsh+dh
                neww = vsw+dw
                if newh<0 or h<=newh or neww<0 or w<=neww: continue
                if dh == 0 and dw==0: continue
                if s[newh][neww] : continue


                if abs(dh)+abs(dw)==1:
                    if dist[newh][neww] > d:
                        dist[newh][neww] = d
                        if newh == gh and neww == gw:
                            return d
                        heapq.heappush(q,(d,newh,neww))
                else:
                    if dist[newh][neww] > d+1:
                        dist[newh][neww] = d+1
                        heapq.heappush(q,(d+1,newh,neww))
    if dist[gh][gw] == INF:
        return -1
    else: return dist[gh][gw]
        
print(solve(h,w,sh,sw,gh,gw,s))

Submission status: Accepted

Solution code:
# string
# a, b, c = input().split()
# str_list = list(input().split())

# number
# a, b, c = map(int, input().split())
# num_list = list(map(int, input().split()))

# lows
# str_list = [input() for _ in range(n)]

# many inputs
# num_list = []
# for i in range(n): num_list.append(list(map(int, input().split())))

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

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

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

inf = int(1e9)
dist = [[inf for j in range(w)] for i in range(h)]
dist[ch][cw] = 0

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

while len(q) != 0:
    i, j = map(int, q.popleft())
    d = dist[i][j]
    
    for v in range(4):
        ni = i + dx[v]
        nj = j + dy[v]

        if ni < 0 or ni >= h or nj < 0 or nj >= w:
            continue
        
        if s[ni][nj] == "#":
            continue

        if dist[ni][nj] <= d:
            continue
        
        dist[ni][nj] = d
        q.appendleft([ni, nj])
    
    for ei in range(-2, 3):
        for ej in range(-2, 3):
            ni = i + ei
            nj = j + ej

            if ni < 0 or ni >= h or nj < 0 or nj >= w:
                continue
        
            if s[ni][nj] == "#":
                continue

            if dist[ni][nj] <= d+1:
                continue

            dist[ni][nj] = d+1
            q.append([ni, nj])

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

Submission status: Accepted

Solution code:
from collections import deque
import math

def solve3(s_flag,h,w,goal_h,goal_w,que):
    while True:
        visited=set()
        while que:
            ch,cw=que.popleft()
            visited.add((ch,cw))
            ## 現在地のコスト
            now=s_flag[ch][cw]
            for d_h,d_w in [(1,0),(0,1),(0,-1),(-1,0)]:
                ## 迷路の外に出ない
                if ch+d_h<0 or h-1<ch+d_h:
                    continue
                if cw+d_w<0 or w-1<cw+d_w:
                    continue
                ## 進行方向のコスト
                dest=s_flag[ch+d_h][cw+d_w]
                if dest!='#': ## 道
                    if dest>now:
                        s_flag[ch+d_h][cw+d_w]=now
                        que.append([ch+d_h,cw+d_w])
        jumping=set()
        for ch,cw in visited:
            now=s_flag[ch][cw]
            for d_h,d_w in [(1,0),(0,1),(0,-1),(-1,0)]:
                jump=[  (d_h+d_w,d_w+d_h),
                        (d_h-d_w,d_w-d_h),
                        (d_h*2,d_w*2),
                        (d_h*2+d_w,d_w*2+d_h),
                        (d_h*2-d_w,d_w*2-d_h),
                        (d_h*2+d_w*2,d_w*2+d_h*2),
                        (d_h*2-d_w*2,d_w*2-d_h*2)]
                for jump_h,jump_w in jump:
                    if ch+jump_h<0 or h-1<ch+jump_h:
                        continue
                    if cw+jump_w<0 or w-1<cw+jump_w:
                        continue
                    jumping.add((ch+jump_h,cw+jump_w))
        if len(jumping)==0:
            break
        for d_jump_h,d_jump_w in jumping:
            ## ワープ先のコスト
            dest_jump=s_flag[d_jump_h][d_jump_w]
            if dest_jump!='#' and dest_jump>now+1:
                s_flag[d_jump_h][d_jump_w]=now+1
                que.append([d_jump_h,d_jump_w])

    # for i in range(h):
    #     print(s_flag[i])
    return s_flag[goal_h][goal_w]

def main():
    h,w=map(int,input().split())
    ch,cw=map(int,input().split())
    ch,cw=ch-1,cw-1
    dh,dw=map(int,input().split())
    dh,dw=dh-1,dw-1
    s=[input() for i in range(h)]
    ## .=0 #=2 visited=1 goal=-1
    # s_flag=[[0 if s[i][j]=='.' else 2 for j in range(w)] for i in range(h)]
    # s_flag[ch][cw]=1
    # s_flag[dh][dw]=-1
    # ans=solve(s_flag,h,w,ch,cw,0)
    # if not ans:
    #     ans=-1
    # else:
    #     ans=ans[-1][2]
    # return ans
    ## .=inf #=# visited=cost
    s_flag=[[math.inf if s[i][j]=='.' else '#' for j in range(w)] for i in range(h)]
    s_flag[ch][cw]=0
    que=deque([[ch,cw]])
    ans=solve3(s_flag,h,w,dh,dw,que)
    if ans==math.inf:
        ans=-1
    return ans

if __name__=='__main__':
    ans=main()
    print(ans)

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())

maze = [list(input()) for _ in range(H)]

que = deque([(0,Ch-1,Cw-1)])
adjecents = [(1,0),(0,1),(-1,0),(0,-1)]
while que:
    step,h,w = que.popleft()
    if h == Dh-1 and w == Dw-1:
        print(step)
        exit()
    if maze[h][w] == "#":
        continue
    else:
        maze[h][w] = "#"
        for a,b in adjecents:
            x = h + a
            y = w + b
            if 0 <= x < H and 0<= y < W:
                if maze[x][y] == ".":
                    que.appendleft((step,x,y))
                else:
                    for i in range(-2,3):
                        for j in range(-2,3):
                            x = h + i
                            y = w + j
                            if 0 <= x < H and 0<= y < W and maze[x][y] == ".":
                                que.append((step+1,x,y))

print(-1)

Submission status: Accepted

Solution code:
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8

@njit((b1[:, :], i8, i8, i8, i8), cache=True)
def main(wall, Sx, Sy, Tx, Ty):
  INF = 1 << 30
  H, W = wall.shape
  S, T = Sx * W + Sy, Tx * W + Ty
  dist = np.full(H * W, INF, np.int64)
  deq = np.empty(2*H*W+100, np.int64)
  dist[S] = 0
  deq[H * W] = S
  l, r = H*W, H*W+1
  while l<r:
    v = deq[l]
    l += 1
    vx,vy = divmod(v,W)
    for dx,dy in ((1,0),(0,1),(-1,0),(0,-1)):
      wx,wy = vx+dx,vy+dy
      if wall[wx,wy]:
        continue
      w = wx * W + wy
      if dist[w] <= dist[v]:
        continue
      dist[w] = dist[v]
      deq[l-1] = w
      l -= 1
    for dx in range(-2,3):
      for dy in range(-2,3):
        wx, wy = vx+dx, vy+dy
        if wall[wx,wy]:
          continue
        w = wx*W+wy
        if dist[w]<=dist[v]+1:
          continue
        dist[w] = dist[v]+1
        deq[r] = w
        r += 1
  ans = dist[T]
  if ans == INF:
    ans = -1
  return ans

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)+1, input().split())
gh, gw = map(lambda x:int(x)+1, input().split())

wall = [0]*(H+4)
wall[0] = [True]*(W+4)
wall[1] = [True]*(W+4)
wall[H+2] = [True]*(W+4)
wall[H+3] = [True]*(W+4)
for h in range(2,H+2):
  wall[h] = [True]*2 + [s=='#' for s in input()] + [True]*2
wall = np.array(wall)
print(main(wall, sh, sw, gh, gw))

Submission status: Accepted

Solution code:
from collections import deque


def solve():
    H, W = map(int, input().split())
    CH, CW = map(int, input().split())
    DH, DW = map(int, input().split())
    S = ["##"+input()+"##" for _ in range(H)]
    for i in range(2):
        S.insert(0, "#"*(W+4))
        S.append("#"*(W+4))

    inf = int(1e9)
    cost = [[inf for _ in range(W+4)] for _ in range(H+4)]
    cost0 = deque()
    ans = -1

    cost0.append((CH+1, CW+1, 0))
    cost[CH+1][CW+1] = 0

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

    cost1 = deque()

    while cost0:
        h, w, c = cost0.popleft()
        cost1.append((h, w, c))

        for i, j in move:
            dh = h+i
            dw = w+j
            if S[dh][dw] == "." and c < cost[dh][dw]:
                cost[dh][dw] = c
                cost0.appendleft((dh, dw, cost[dh][dw]))

        if len(cost0) == 0:
            while cost1:
                h, w, c = cost1.popleft()
                for i, j in warp:
                    dh = h+i
                    dw = w+j
                    if S[dh][dw] == "." and c+1 < cost[dh][dw]:
                        cost[dh][dw] = c+1
                        cost0.append((dh, dw, cost[dh][dw]))

        if cost[DH+1][DW+1] != inf:
            ans = cost[DH+1][DW+1]

    print(ans)


if __name__ == "__main__":
    solve()

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())

l = [[1 if i=="#" else 0 for i in input()] for _ in range(H)]
q = deque([(0, (Ch-1, Cw-1))])
INF = 10**12
costs = [[INF]*W for _ in range(H)]
costs[Ch-1][Cw-1] = 0

while q:
    cost, pos = q.popleft()
    h, w = pos
    for dh in range(-2, 3):
        for dw in range(-2, 3):
            if dh==0 and dw==0:
                continue
            hh, ww = h+dh, w+dw
            if not (0<=hh<H and 0<=ww<W):
                continue
            if l[hh][ww]:
                continue
            
            if ((abs(dh)==1 and dw==0) or (dh==0 and abs(dw)==1)) and costs[hh][ww] > costs[h][w]:
                costs[hh][ww] = costs[h][w]
                q.appendleft((cost, (hh, ww)))
            elif costs[hh][ww] > costs[h][w]+1:
                costs[hh][ww] = costs[h][w]+1
                q.append((cost+1, (hh, ww)))

ans = costs[Dh-1][Dw-1]
print(ans if ans!=INF else -1)