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: Runtime Error

Solution code:
import sys
import re
import queue
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []


H, W = i_map()
Ch, Cw = i_map()
Dh, Dw = i_map()
Ch,Cw = Ch-1,Cw-1
Dh,Dw = Dh-1,Dw-1
maze = [input() for _ in range(H)]

INF = 10 ** 12
path = [[INF] * W for _ in range(H)]  # path: 各マスへの移動コスト

# walk:移動A, warp:移動B
walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]

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

while q:
    x, y, s = q.popleft()
    for dx, dy in walk:  # 移動A
        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))  # 移動Aの場合はコスト0. キューの先頭に追加する.
    for dx, dy in warp:  # 移動B
        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))  # 移動Bの場合はコスト1. キューの最後尾に追加する.
    
ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
print(ans)


if __name__ == '__main__':
	main()

Submission status: Runtime Error

Solution code:
from collections import deque
h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())

M = ['##' + input() + '##' for _ in range(h)]
for i in range(2):
    M.insert(0,'#'*(w+4))
    M.append('#'*(w+4))

INF = float('inf')
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 M[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)

Submission status: Runtime Error

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

INF = 10**12

#各マスへの移動コスト
path = [[INF] * W for _ in range(H)]

#walk:移動A　warp:移動B
walk = [(0, 1), (0, 1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0,0) + walk]]

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

while q : 
    x, y, s = q.popleft()
    #移動A
    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
            #移動Aの場合はコスト0, キューの先頭に追加する
            q.appendleft((nx, ny, s))
    #移動B
    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
            #移動Bの場合はコスト1, キューの最後尾に追加
            q.appendleft((nx, ny, s+1))
ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

def solve():
  h,w=map(int,input().split())
  cx,cy=map(int,input().split())
  dx,dy=map(int,input().split())

  M=[]
  for i in range(2):
    M.append("#"*(w+4))
  for i in range(h):
    M.append("##"+input()+"##")
  for i in range(2):
    M.append("#"*(w+4))

  INF=10**6
  C=[[INF for _ in range(w+4)] for _ in range(h+4)]
  C[-~cy][-~cx]=0
  QA,QB=deque(),deque()
  QA.append((-~cy,-~cx,0))
  W=[[i,j] for i in range(-2,3) for j in range(-2,3) if abs(i)+abs(j)>1]

  while QA:
    h,w,c=QA.popleft()
    QB.append((h,w,c))

    for i,j in [[1,0],[0,1],[-1,0],[0,-1]]:
      dh,dw=h+i,w+j
      if M[dh][dw]=="." and c<C[dh][dw]:
        C[dh][dw]=c
        QA.appendleft((dh,dw,c))

    if QA:
      continue

    while QB:
      h,w,c=QB.popleft()
      for i,j in W:
        dh,dw=h+i,w+j
        if M[dh][dw]=="." and -~c<C[dh][dw]:
          C[dh][dw]=-~c
          QA.append((dh,dw,-~c))

  print(C[-~dy][-~dx] if C[-~dy][-~dx]!=INF else -1)

if __name__ == "__main__":
  solve()

Submission status: Runtime Error

Solution code:
import sys
import queue

INF = -100000

H, W = [int(x) for x in input().split()]
C = [int(x)-1 for x in input().split()]
D = [int(x)-1 for x in input().split()]
S = [[str(x) for x in list(input())] for _ in range(H)]

dx = [1, 0, -1, 0]; dy = [0, 1, 0, -1]
dx2 = [0, 1, -1, 2, -2]; dy2 = [0, 1, -1, 2, -2]

def BFS(start, ans, flag):
  Q = queue.Queue()
  Q.put(start)
  flag[C[0]][C[1]] = ans
  
  Next = list()
  while not Q.empty():
    q = Q.get()
    if(q[0]==D[0])and(q[1]==D[1]):
      print(ans)
      sys.exit()
    for i in range(4):
      nx = q[0] + dx[i]; ny = q[1] + dy[i]
      if(0<=nx<W and 0<=ny<H and S[nx][ny]!='#' and flag[nx][ny]==INF):
        Q.put([nx, ny])
        flag[nx][ny] = flag[q[0]][q[1]]
      elif(0<=nx<W and 0<=ny<H and S[nx][ny]=='#'):
        Next.append(q)
  return flag, Next

def PlanB(flag, Next):
  for l in range(len(Next)):
    for i in range(5):
      for j in range(5):
        nx, ny = Next[l][0] + dx2[i], Next[l][1] + dy2[j]
        if(0<=nx<W and 0<=ny<H and S[nx][ny]!='#' and flag[nx][ny]==INF):
          return [nx, ny]
  return [-1,-1]
       

if __name__=='__main__':
  ans = 0
  flag = [[INF for i in range(W)] for i in range(H)]
  start = C
  while start[0]!=(-1):
    flag, Next = BFS(start, ans, flag)
    start = PlanB(flag, Next)
    ans += 1
  print(-1)

Submission status: Runtime Error

Solution code:
import sys
import queue

INF = -100000

H, W = [int(x) for x in input().split()]
C = [int(x)-1 for x in input().split()]
D = [int(x)-1 for x in input().split()]
S = [[str(x) for x in list(input())] for _ in range(H)]

dx = [1, 0, -1, 0]; dy = [0, 1, 0, -1]
dx2 = [0, 1, -1, 2, -2]; dy2 = [0, 1, -1, 2, -2]

def BFS(start, ans, flag):
  Q = queue.Queue()
  Q.put(start)
  flag[C[0]][C[1]] = ans
  
  Next = list()
  while not Q.empty():
    q = Q.get()
    if(q[0]==D[0])and(q[1]==D[1]):
      print(ans)
      sys.exit()
    for i in range(4):
      nx = q[0] + dx[i]; ny = q[1] + dy[i]
      if(0<=nx<W and 0<=ny<H and S[nx][ny]!='#' and flag[nx][ny]==INF):
        Q.put([nx, ny])
        flag[nx][ny] = flag[q[0]][q[1]]
      elif(0<=nx<W and 0<=ny<H and S[nx][ny]=='#'):
        Next.apppend(q)
  return flag, Next

def PlanB(flag, Next):
  for l in range(len(nij)):
    for i in range(5):
      for j in range(5):
        nx, ny = Next[l][0] + dx2[i], Next[l][1] + dy2[j]
        if(0<=nx<W and 0<=ny<H and S[nx][ny]!='#' and flag[nx][ny]==INF):
          return [nx, ny]
  return [-1,-1]
       

if __name__=='__main__':
  ans = 0
  flag = [[INF for i in range(W)] for i in range(H)]
  start = C
  while start[0]!=(-1):
    flag, Next = BFS(start, ans, flag)
    start = PlanB(flag, Next)
    ans += 1
  print(-1)

Submission status: Runtime Error

Solution code:
import sys
import queue

INF = -100000

H, W = [int(x) for x in input().split()]
C = [int(x)-1 for x in input().split()]
D = [int(x)-1 for x in input().split()]
S = [[str(x) for x in list(input())] for _ in range(H)]

dx = [1, 0, -1, 0]; dy = [0, 1, 0, -1]
dx2 = [0, 1, -1, 2, -2]; dy2 = [0, 1, -1, 2, -2]

def BFS(start, ans, flag):
  Q = queue.Queue()
  Q.put(start)
  flag[C[0]][C[1]] = ans
  
  while not Q.empty():
    q = Q.get()
    if(q[0]==D[0])and(q[1]==D[1]):
      print(ans)
      sys.exit()
    for i in range(4):
      nx = q[0] + dx[i]; ny = q[1] + dy[i]
      if(0<=nx<W and 0<=ny<H and S[nx][ny]!='#' and flag[nx][ny]==INF):
        Q.put([nx, ny])
        flag[nx][ny] = flag[q[0]][q[1]]
  return flag

def PlanB(flag):
  nij = list()
  for i in range(H):
    for j in range(W):
      if(flag[i][j] != INF):
        nij.append([i,j])
  for l in range(len(nij)):
    for i in range(5):
      for j in range(5):
        nx, ny = nij[l][0] + dx2[i], nij[l][1] + dy2[j]
        if(0<=nx<W and 0<=ny<H and S[nx][ny]!='#' and flag[nx][ny]==INF):
          return [nx, ny]
  return [-1,-1]
       

if __name__=='__main__':
  ans = 0
  flag = [[INF for i in range(W)] for i in range(H)]
  start = C
  while start[0]!=(-1):
    flag = BFS(start, ans, flag)
    start = PlanB(flag)
    ans += 1
  print(-1)

Submission status: Runtime Error

Solution code:
from collections import deque

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

maze = [input() for _ in range(H)]
visit = [[-1] * W for _ in range(H)]
visit[Ch][Cw] = 0

DQ = deque([[Ch, Cw]])
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

while DQ:
  px, py = DQ.popleft()
  if px==Dh and py==Dw:
    print(visit[px][py])
    exit()
  
  for i in range(4):
    nx = px + dx[i]
    ny = py + dy[i]
    if 0<=nx<=H-1 and 0<=ny<=C-1 and maze[nx][ny]=="." and  (visit[nx][ny]>visit[px][py] or visit[nx][ny]==-1):
      visit[nx][ny] = visit[px][py]
      DQ.append([nx, ny])
    
  for i in range(-2, 3):
    for j in range(-2, 3):
      if i==j==0:
        continue
      nx = px + i
      ny = py + j
      if 0<=nx<=H-1 and 0<=ny<=C-1 and maze[nx][ny]=="." and visit[nx][ny]==-1:
        visit[nx][ny] = visit[px][py] + 1
        DQ.append([nx, ny])

print(-1)

Submission status: Runtime Error

Solution code:
import copy
from collections import deque
H,W = map(int, input().split())
Ch,Cw = map(int, input().split())
Dh,Dw = map(int, input().split())
maze = []
vis=[]
stack = deque([[Ch-1,Cw-1]])

for h in range(H):
  maze.append(list(input()))
  vis.append([1e9]*W)

vis[Ch-1][Cw-1] = 0

while stack:
  p = stack.popleft()
  a = p[0]
  b = p[1]
  dis = vis[a][b]
  
  for i in range(-2,3):
    for j in range(-2,3):
      if 0<= a+i <H and 0<= b+j <W:
        if maze[a+i][b+j]=="#":
          continue
          
        if 0<i*i+j*j<=1:
          if vis[a+i][b+j]<=dis:
            continue
          vis[a+i][b+j] = dis
          stack.appendleft([a+i,b+j])
          
        elif i*i+j*j > 1:
          if vis[a+i][b+j] <= dis+1:
            continue
          vis[a+i][b+j] = dis+1
          stack.append([a+i,b+j])
          
if vis[Dh-1][Dw-1]!=1e9:
  print(vis[Dh-1][Dw-1])
else:
  print(ans)

Submission status: Runtime Error

Solution code:
from sys import stdin
from math import ceil
inp = lambda : stdin.readline().strip()

X = [0,1,0,-1]
Y = [-1,0,1,0]
def isValid(x,y):
    if x >= 0 and y >= 0 and x < h  and y < w:
        return True
    return False


def dfs_iter(x,y):
    stack = [(x,y)]
    while stack:
        x,y = stack.pop()
        if isValid(x,y) and visited[x][y] == -1 and  maze[x][y] != '#':
            visited[x][y] = curr
            for i,j in zip(X,Y):
                if isValid(x+i,y+j) and visited[x+i][y+j] == -1  and maze[x+i][y+j] != '#':
                    stack.append((x+i,y+j))
def dfs(n):
    stack = [n]
    depths = [0]
    while stack:
        node = stack.pop()
        depth = depths.pop()
        if not visited2[node]:
            visited2[node] = True
            if node == visited[dh-1][dw-1]:
                return depth
            for child in adj[node]:
                if not visited2[child]:
                    stack.append(child)
                    depths.append(depth+1)
    return -1


h, w = [int(x) for x in inp().split()]
ch,cw = [int(x) for x in inp().split()]
dh, dw = [int(x) for x in inp().split()]
visited  = [[-1]*w for x in range(h)]

maze = []
adj = [set() for i in range(ceil(h*w/2))]
visited2 = [False]*(ceil(h*w/2))
for i in range(h):
    maze.append(list(inp()))

curr = 0
for i in range(h):
    for j in range(w):
        if visited[i][j] == -1 and maze[i][j] != '#':
            dfs_iter(i,j)
            curr += 1
for i in range(h):
    for j in range(w):
        if maze[i][j] != '#':
            for k in range(-2,3):
                for l in range(-2,3):
                    if not (k==l and l == 0):
                        if isValid(i+k,j + l) and visited[l][k] != visited[i+k][j+l] and maze[i+k][j+l] != '#':
                            adj[visited[i][j]].add(visited[i+k][j+l])

print(dfs(visited[ch-1][cw-1]))

Submission status: Runtime Error

Solution code:
############################################################
import sys
f = open('input.txt', 'r')
sys.stdin = f
############################################################

import queue

H, W = list(map(int, input().split()))
S = list(map(int, input().split()))
G = list(map(int, input().split()))
S = [S[0] - 1, S[1] - 1]
G = [G[0] - 1, G[1] - 1]

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

MAX = 1000001
cost_list = [[MAX] * W for i in range(H)]


to_walk = queue.Queue()
to_warp = queue.Queue()

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


def walk(z):
    h, w = z
    cost = cost_list[h][w]
    for [p, q] in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
        if (0 <= h + p < H) and (0 <= w + q < W):
            if maze[h + p][w + q] == ".":
                if cost_list[h + p][w + q] > cost:
                    cost_list[h + p][w + q] = cost
                    to_walk.put([h + p, w + q])
            else:
                to_warp.put([h, w])


def warp(z):
    h, w = z
    cost = cost_list[h][w] + 1
    for [p, q] in warp_directions:
        if (0 <= h + p < H) and (0 <= w + q < W):
            if maze[h + p][w + q] == "." and cost_list[h + p][w + q] > cost:
                cost_list[h + p][w + q] = cost
                to_walk.put([h + p, w + q])


to_walk.put(S)
cost_list[S[0]][S[1]] = 0

while True:
    while not to_walk.empty():
        walk(to_walk.get())
    while not to_warp.empty():
        warp(to_warp.get())
    if to_walk.empty() and to_warp.empty():
        break

if cost_list[G[0]][G[1]] == MAX:
    print(-1)
else:
    print(cost_list[G[0]][G[1]])

Submission status: Runtime Error

Solution code:
############################################################
import sys
f = open('input.txt', 'r')
sys.stdin = f
############################################################

import queue

H, W = list(map(int, input().split()))
S = list(map(int, input().split()))
G = list(map(int, input().split()))
S = [S[0] - 1, S[1] - 1]
G = [G[0] - 1, G[1] - 1]

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

MAX = 1000001
cost_list = [[MAX] * W for i in range(H)]


to_walk = queue.Queue()
to_warp = queue.Queue()


def walk(z):
    h, w = z
    cost = cost_list[h][w]
    wall = 0
    for [p, q] in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
        if (0 <= h + p < H) and (0 <= w + q < W):
            if maze[h + p][w + q] == ".":
                if cost_list[h + p][w + q] > cost:
                    cost_list[h + p][w + q] = cost
                    to_walk.put([h + p, w + q])
            else:
                wall += 1
                
    if wall > 1:
        to_warp.put([h, w])


def warp(z):
    h, w = z
    cost = cost_list[h][w] + 1
    for [p, q] in [[-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]]:
        if (0 <= h + p < H) and (0 <= w + q < W):
            if maze[h + p][w + q] == "." and cost_list[h + p][w + q] > cost:
                cost_list[h + p][w + q] = cost
                to_walk.put([h + p, w + q])


to_walk.put(S)
cost_list[S[0]][S[1]] = 0

while True:
    while not to_walk.empty():
        walk(to_walk.get())
    while not to_warp.empty():
        warp(to_warp.get())
    if to_walk.empty() and to_warp.empty():
        break

if cost_list[G[0]][G[1]] == MAX:
    print(-1)
else:
    print(cost_list[G[0]][G[1]])

Submission status: Runtime Error

Solution code:
############################################################
import sys
f = open('input.txt', 'r')
sys.stdin = f
############################################################

import queue

H, W = list(map(int, input().split()))
S = list(map(int, input().split()))
G = list(map(int, input().split()))
S = [S[0] - 1, S[1] - 1]
G = [G[0] - 1, G[1] - 1]

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

MAX = 1000001
cost_list = [[MAX] * W for i in range(H)]


to_walk = queue.Queue()
to_warp = queue.Queue()


def walk(z):
    h, w = z
    cost = cost_list[h][w]
    for [p, q] in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
        if (0 <= h + p < H) and (0 <= w + q < W):
            if maze[h + p][w + q] == "." :
                if cost_list[h + p][w + q] > cost:
                    cost_list[h + p][w + q] = cost
                    to_walk.put([h + p, w + q])
            else:
                to_warp.put([h, w])


def warp(z):
    h, w = z
    cost = cost_list[h][w] + 1
    for [p, q] in [[-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]]:
        if (0 <= h + p < H) and (0 <= w + q < W):
            if maze[h + p][w + q] == "." and cost_list[h + p][w + q] > cost:
                cost_list[h + p][w + q] = cost
                to_walk.put([h + p, w + q])


to_walk.put(S)
cost_list[S[0]][S[1]] = 0

while True:
    while not to_walk.empty():
        walk(to_walk.get())
    while not to_warp.empty():
        warp(to_warp.get())
    if to_walk.empty() and to_warp.empty():
        break

if cost_list[G[0]][G[1]] == MAX:
    print(-1)
else:
    print(cost_list[G[0]][G[1]])

Submission status: Runtime Error

Solution code:
############################################################
import sys
f = open('input.txt', 'r')
sys.stdin = f
############################################################

import queue

H, W = list(map(int, input().split()))
S = list(map(int, input().split()))
G = list(map(int, input().split()))
S = [S[0] - 1, S[1] - 1]
G = [G[0] - 1, G[1] - 1]

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

INF = 10000000
cost_list = [[INF] * W for i in range(H)]


to_walk = queue.Queue()
to_warp = queue.Queue()


def walk(z):
    x, y = z
    cost = cost_list[y][x]
    to_warp.put([x, y])
    for [p, q] in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
        if (0 <= x + p < W) and (0 <= y + q < H):
            if maze[y + q][x + p] == "." and cost_list[y + q][x + p] > cost:
                cost_list[y + q][x + p] = cost
                to_walk.put([x + p, y + q])
                to_warp.put([x + p, y + q])


def warp(z):
    x, y = z
    cost = cost_list[y][x] + 1
    for [p, q] in [[-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]]:
        if (0 <= x + p < W) and (0 <= y + q < H):
            if maze[y + q][x + p] == "." and cost_list[y + q][x + p] > cost:
                cost_list[y + q][x + p] = cost
                to_walk.put([x + p, y + q])


to_walk.put(S)
cost_list[S[0]][S[1]] = 0

while True:
    while not to_walk.empty():
        walk(to_walk.get())
    while not to_warp.empty():
        warp(to_warp.get())
    if to_walk.empty() and to_warp.empty():
        break

if cost_list[G[0]][G[1]] == INF:
    print(-1)
else:
    print(cost_list[G[0]][G[1]])

Submission status: Runtime Error

Solution code:
############################################################
import sys
f = open('input.txt', 'r')
sys.stdin = f
############################################################

import queue

H, W = list(map(int, input().split()))
S = list(map(int, input().split()))
G = list(map(int, input().split()))
S = [S[0] - 1, S[1] - 1]
G = [G[0] - 1, G[1] - 1]

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

INF = 1000000
cost_list = [[INF] * W for i in range(H)]


to_walk = queue.Queue()
to_warp = queue.Queue()


def walk(z):
    x, y = z
    cost = cost_list[y][x]
    to_warp.put([x, y])
    for [p, q] in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
        if (0 <= x + p < W) and (0 <= y + q < H):
            if maze[y + q][x + p] == "." and cost_list[y + q][x + p] > cost:
                cost_list[y + q][x + p] = cost
                to_walk.put([x + p, y + q])
                to_warp.put([x + p, y + q])


def warp(z):
    x, y = z
    cost = cost_list[y][x] + 1
    for [p, q] in [[-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]]:
        if (0 <= x + p < W) and (0 <= y + q < H):
            if maze[y + q][x + p] == "." and cost_list[y + q][x + p] > cost:
                cost_list[y + q][x + p] = cost
                to_walk.put([x + p, y + q])


to_walk.put(S)
cost_list[S[0]][S[1]] = 0

while True:
    while not to_walk.empty():
        walk(to_walk.get())
    while not to_warp.empty():
        warp(to_warp.get())
    if to_walk.empty() and to_warp.empty():
        break

if cost_list[G[0]][G[1]] == INF:
    print(-1)
else:
    print(cost_list[G[0]][G[1]])

Submission status: Runtime Error

Solution code:
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 i in range(h):
  t = input()
  s.append(t)

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

queue = deque([[ch,cw]])
visited = [[False for i in range(w)] for j in range(h)]
magic = [[-1 for i in range(w)] for j in range(h)]
visited[ch][cw] = True
magic[ch][cw] = 0
while queue:
  l,m = queue.popleft()
  for k in range(4):
    x = l + dx[k]
    y = m + dy[k]
    if x < 0 or y < 0 or x >= h or y >= w or visited[x][y] or s[x][y] == "#":
      continue
    #visited[x][y] = visited[l][m] + 1
    visited[x][y] = True
    magic[x][y] = magic[l][m]
    queue.append([x,y])
  if len(queue) == 0:
    for i in range(-2,3):
      for j in range(-2,3):
        if (i== 1 and j == 0)or(i==-1 and j == 0)or(i==0 and j == 1)or(i==0 and j==-1)or(i==0 and j==0):
          continue
        x = l + i
        y = m + j
        if x < 0 or y < 0 or x >= h or y >= w or visited[x][y] or s[x][y] == "#":
          continue
        visited[x][y] = True
        magic[x][y] = magic[l][m] + 1
        queue.append([x,y])
        cnt += 1
print (magic[dh][dw])

Submission status: Runtime Error

Solution code:
import sys
import pprint
import time
h,w = map(int,input().split())
sh,sw = map(int,input().split())
gh,gw = map(int,input().split())
C = [list(input()) for _ in range(h)]
dist = [[-1] * w for _ in range(h)] 
sh-=1
sw-=1
gh-=1
gw-=1

move = [[-1, 0], [1, 0], [0, -1], [0, 1]]
magic = [[-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]]

for i in range(h):
    for j in range(w):
        if C[i][j] == '#':
            dist[i][j] = -2

def dfs(spos, check_list, dp):
    queue = []
    queue.append(spos)
    dist[spos[0]][spos[1]] = dp
    if spos == [gh, gw]:
        return True
    while len(queue) > 0:
        x, y = queue.pop(0)
        check_list.append([x,y])
        for p, q in move:
            nx = x + p
            ny = y + q
            if 0 <= nx < h and 0 <= ny < w and dist[nx][ny] == -1:
                dist[nx][ny] = dp
                queue.append([nx,ny])
                check_list.append([nx,ny])
                if [nx, ny] == [gh, gw]:
                    return True
    return False

def magic_dfs(check_list, ndp):
    next_check_list = []
    while len(check_list) > 0:
        x, y = check_list.pop(0) 
        for p, q in magic:
            nx = x + p
            ny = y + q
            if 0 <= nx < h and 0 <= ny < w and dist[nx][ny] == -1:
                found = dfs([nx, ny], next_check_list, ndp)
                if found:
                    return True
    
    if next_check_list:
        magic_dfs(next_check_list, ndp+1)
    
    return False

def solve():
    check_list = []
    found = dfs([sh,sw], check_list, 0)
    if not found:
        magic_dfs(check_list, 1)

#pprint.pprint(dist)
solve()
#pprint.pprint(dist)
print(dist[gh][gw])

Submission status: Runtime Error

Solution code:
import sys
import pprint
import time
h,w = map(int,input().split())
sh,sw = map(int,input().split())
gh,gw = map(int,input().split())
C = [list(input()) for _ in range(h)]
dist = [[-1] * w for _ in range(h)] 
sh-=1
sw-=1
gh-=1
gw-=1

move = [[-1, 0], [1, 0], [0, -1], [0, 1]]
magic = [[-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]]

for i in range(h):
    for j in range(w):
        if C[i][j] == '#':
            dist[i][j] = -2

def dfs(spos, check_list, dp):
    queue = []
    queue.append(spos)
    dist[spos[0]][spos[1]] = dp
    while len(queue) > 0:
        x, y = queue.pop(0)
        check_list.append([x,y])
        for p, q in move:
            nx = x + p
            ny = y + q
            if 0 <= nx < h and 0 <= ny < w and dist[nx][ny] == -1:
                dist[nx][ny] = dp
                queue.append([nx,ny])
                check_list.append([nx,ny])
                if [nx, ny] == [gh, gw]:
                    return True
    return False

def magic_dfs(check_list, ndp):
    next_check_list = []
    while len(check_list) > 0:
        x, y = check_list.pop(0) 
        for p, q in magic:
            nx = x + p
            ny = y + q
            if 0 <= nx < h and 0 <= ny < w and dist[nx][ny] == -1:
                found = dfs([nx, ny], next_check_list, ndp)
                if found:
                    return True
    
    if next_check_list:
        magic_dfs(next_check_list, ndp+1)
    
    return False

def solve():
    check_list = []
    found = dfs([sh,sw], check_list, 0)
    if not found:
        magic_dfs(check_list, 1)

#pprint.pprint(dist)
solve()
#pprint.pprint(dist)
print(dist[gh][gw])

Submission status: Runtime Error

Solution code:
from heapq import heapify,heappush,heappop

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

S = [list(input()) for i in range(H)]
cnt = [[10**10 for i in range(W)] for j in range(H)]

task_list = []
heapify(task_list)
heappush(task_list,[0,sx,sy])
S[sy][sx]="."

for i in range(H):
    for j in range(W):
        if S[i][j]=="#":
            cnt[i][j]=-1

check = [[0 for i in range(W)] for j in range(H)]
count = 0
while len(task_list)>0:
    t,x,y = heappop(task_list)
    check[x][y]+=1
    if x==gx and y==gy:
        print(t)
        exit()
    
    if x<0 or W<=x or y<0 or H<=y:
        continue

    if S[y][x] != ".":
        continue

    S[y][x]=str(t)#確定最低値
    cnt[y][x]=t#暫定最低値

    for i in range(-2,3):
        for j in range(-2,3):
            if abs(i)+abs(j) < 2:
                if not(x+i<0 or W<=x+i or y+j<0 or H<=y+j):
                    if S[y+j][x+i]=="." and cnt[y+j][x+i] > t:
                        heappush(task_list,[t,x+i,y+j])
                        cnt[y+j][x+i]=t
            if not(x+i<0 or W<=x+i or y+j<0 or H<=y+j):
                if S[y+j][x+i]=="." and cnt[y+j][x+i] > t+1:
                    heappush(task_list,[t+1,x+i,y+j])
                    cnt[y+j][x+i]=t+1

print(-1)

Submission status: Runtime Error

Solution code:
import numpy as np
from heapq import *

H, W = map(int, input().split())
sy, sx = map(lambda x: int(x) - 1, input().split())
ty, tx = map(lambda x: int(x) - 1, input().split())
s, t = sy * H + sx, ty * H + tx
graph = [input() for _ in range(H)]

INF = 1 << 30
dist = np.full(H * W, INF, np.int64)
que = []

def push(v, d):
    if(dist[v] <= d):
        return
    dist[v] = d
    heappush(que, (d, v))

def move(ny, nx, d):
    if ny < 0 or ny >= H or nx < 0 or nx >= W:
        return
    if graph[ny][nx] == '.':
        push(ny * H + nx, d)

push(s, 0)

while que:
    d, v = heappop(que)
    if d > dist[v]:
        continue
    y, x = divmod(v, H)
    for dy in range(-2, 3):
        for dx in range(-2, 3):
            move(y + dy, x + dx, d + (abs(dy) + abs(dx) > 1))

if dist[t] == INF:
    print(-1)
else:
    print(dist[t])