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  math
from heapq import *
import fractions
import bisect
from collections import deque
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

INF=10**9
H,W=nm()
sx,sy=nm()
gx,gy=nm()
mass=[[0 for i in range(1000)] for j in range(1000)]
edge1=[[[] for i in range(1000)] for j in range(1000)]
edge2=[[[] for i in range(1000)] for j in range(1000)]

def bfs(start,edge1,edge2):
    d=[[INF for i in range(1000)] for j in range(1000)]
    d[start[0]][start[1]]=0
    q=deque([start])
    while (q):
        e=q.popleft()
        for i,j in edge1[e[0]][e[1]]:
            if(d[e[0]][e[1]]<d[i][j]):
                d[i][j]=d[e[0]][e[1]]
                q.appendleft((i,j))   
        for i,j in edge2[e[0]][e[1]]:
            if(d[e[0]][e[1]]+1<d[i][j]):
                d[i][j]=d[e[0]][e[1]]+1
                q.append((i,j))   
    return d

for i in range(H):
    t=list(ns())
    for j in range(W):
        if(t[j]=='.'):
            mass[i][j]=1

for i in range(H):
    for j in range(W):
        for k in range(-2,3):
            for l in range(-2,3):
                if((k==0 and l==0) or i+k<0 or j+l<0):
                    continue
                else:
                    if(mass[i+k][j+l]==1):
                        if(abs(k)^2+abs(l)^2==1):
                            edge1[i][j].append((i+k,j+l))
                        else:
                            edge2[i][j].append((i+k,j+l))


start=[sx-1,sy-1]
d=bfs(start,edge1,edge2)
print(d[gx-1][gy-1])

Submission status: Runtime Error

Solution code:
from collections import deque

def is_okay(x, y, H, W):
    if x>=0 and x<=W-1:
        if y>=0 and y <=H-1:
            return True
        else:
            return False
    else:
        return False

def main():
    H, W = list(map(int, input().split()))
    Ch, Cw = list(map(int, input().split()))
    Dh, Dw = list(map(int, input().split()))
    S = []
    for i in range(H):
        S.append(list(input()))

    visited = [[False for _ in range(H)] for _ in range(W)]

    queue_global = deque([[Ch-1, Cw-1]])
    queue_local = deque()
    goal = [Dh-1, Dw-1]

    ans = 0

    while len(queue_global) > 0:
        while len(queue_global) > 0:
            queue_local.append(queue_global.popleft())
        new_visit = []
        while len(queue_local) > 0:
            x, y = queue_local.popleft()
            new_visit.append([x, y])
            visited[x][y] = True
            if [x, y] == goal:
                print(ans)
                exit()
            else:
                if x+1 < W-1 and visited[x+1][y] == False:
                    if S[y][x+1] == ".":
                        queue_local.append([x+1, y])
                if x > 0 and visited[x-1][y] == False:
                    if S[y][x-1] == ".":
                        queue_local.append([x-1, y])
                if y+1 < H-1 and visited[x][y+1] == False:
                    if S[y+1][x] == ".":
                        queue_local.append([x, y+1])
		if y > 0 and visited[x][y-1] == False:
                    if S[y-1][x] == ".":
                        queue_local.append([x, y-1])

        ans += 1
        for x,y in new_visit:
            candidates = []
            for i in range(-2,3):
		for j in range(-2,3):
                    candidates.append([x+i, y+j])
            for item in candidates:
                x_new = item[0]
                y_new = item[1]
                if is_okay(x_new, y_new, H, W):
                    if S[y_new][x_new] == ".":
                        if visited[x_new][y_new] == False:
                            queue_global.append([x_new, y_new])
        print(new_visit)

    print("-1")

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from heapq import heapify, heappush, heappop
import numpy as np
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
from scipy.special import comb
import copy
import networkx as nx
import numba
from numba import njit, b1, i4, i8, f8
sys.setrecursionlimit(10**6)

# lis_of_lis = [[] for _ in range(N)]


def zz():
    return list(map(int, sys.stdin.readline().split()))


def z():
    return int(sys.stdin.readline())


def S():
    return sys.stdin.readline()[:-1]


def C(line):
    return [sys.stdin.readline() for _ in range(line)]


@njit((b1[:, :], i8, i8, i8, i8), cache=True)
def main(H, W, c_h, c_w, d_h, d_w):

    que = deque([(c_h, c_w)])
    INF = 1e9
    dist = [[INF]*W for _ in range(H)]
    dist[c_h][c_w] = 0
    while que:
        # print(que)
        tmp = que.popleft()
        h, w = tmp
        d = dist[h][w]
        for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            new_h = h + dy
            new_w = w + dx
            if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                continue
            if board[new_h][new_w] == '#':
                continue
            if dist[new_h][new_w] <= d:
                continue
            dist[new_h][new_w] = d
            que.appendleft((new_h, new_w))
        # 魔法
        for m_dy in range(-2, 3):
            for m_dx in range(-2, 3):
                new_h = h + m_dy
                new_w = w + m_dx
                if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                    continue
                if board[new_h][new_w] == '#':
                    continue
                if dist[new_h][new_w] <= d + 1:
                    continue
                dist[new_h][new_w] = d + 1
                que.append((new_h, new_w))

    ans = dist[d_h][d_w]
    if ans == INF:
        print(-1)
    else:
        print(ans)


H, W = zz()
c_h, c_w = zz()
d_h, d_w = zz()
board = []
c_h -= 1
c_w -= 1
d_h -= 1
d_w -= 1
for i in range(H):
    tmp = S()
    board.append(tmp)
main(H, W, c_h, c_w, d_h, d_w)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from heapq import heapify, heappush, heappop
import numpy as np
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
from scipy.special import comb
import copy
import networkx as nx
import numba
from numba import njit, b1, i4, i8, f8
sys.setrecursionlimit(10**6)

# lis_of_lis = [[] for _ in range(N)]


def zz():
    return list(map(int, sys.stdin.readline().split()))


def z():
    return int(sys.stdin.readline())


def S():
    return sys.stdin.readline()[:-1]


def C(line):
    return [sys.stdin.readline() for _ in range(line)]


@njit((b1[:, :], i8, i8, i8, i8), cache=True)
def main():
    H, W = zz()

    c_h, c_w = zz()
    d_h, d_w = zz()
    board = []
    c_h -= 1
    c_w -= 1
    d_h -= 1
    d_w -= 1
    for i in range(H):
        tmp = S()
        board.append(tmp)

    que = deque([(c_h, c_w)])
    INF = 1e9
    dist = [[INF]*W for _ in range(H)]
    dist[c_h][c_w] = 0
    while que:
        # print(que)
        tmp = que.popleft()
        h, w = tmp
        d = dist[h][w]
        for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            new_h = h + dy
            new_w = w + dx
            if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                continue
            if board[new_h][new_w] == '#':
                continue
            if dist[new_h][new_w] <= d:
                continue
            dist[new_h][new_w] = d
            que.appendleft((new_h, new_w))
        # 魔法
        for m_dy in range(-2, 3):
            for m_dx in range(-2, 3):
                new_h = h + m_dy
                new_w = w + m_dx
                if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                    continue
                if board[new_h][new_w] == '#':
                    continue
                if dist[new_h][new_w] <= d + 1:
                    continue
                dist[new_h][new_w] = d + 1
                que.append((new_h, new_w))

    ans = dist[d_h][d_w]
    if ans == INF:
        print(-1)
    else:
        print(ans)


main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from heapq import heapify, heappush, heappop
import numpy as np
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
from scipy.special import comb
import copy
import networkx as nx
sys.setrecursionlimit(10**6)

# lis_of_lis = [[] for _ in range(N)]


def zz():
    return list(map(int, sys.stdin.readline().split()))


def z():
    return int(sys.stdin.readline())


def S():
    return sys.stdin.readline()[:-1]


def C(line):
    return [sys.stdin.readline() for _ in range(line)]


@njit((b1[:, :], i8, i8, i8, i8), cache=True)
def main():
    H, W = zz()

    c_h, c_w = zz()
    d_h, d_w = zz()
    board = []
    c_h -= 1
    c_w -= 1
    d_h -= 1
    d_w -= 1
    for i in range(H):
        tmp = S()
        board.append(tmp)

    que = deque([(c_h, c_w)])
    INF = 1e9
    dist = [[INF]*W for _ in range(H)]
    dist[c_h][c_w] = 0
    while que:
        # print(que)
        tmp = que.popleft()
        h, w = tmp
        d = dist[h][w]
        for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            new_h = h + dy
            new_w = w + dx
            if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                continue
            if board[new_h][new_w] == '#':
                continue
            if dist[new_h][new_w] <= d:
                continue
            dist[new_h][new_w] = d
            que.appendleft((new_h, new_w))
        # 魔法
        for m_dy in range(-2, 3):
            for m_dx in range(-2, 3):
                new_h = h + m_dy
                new_w = w + m_dx
                if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                    continue
                if board[new_h][new_w] == '#':
                    continue
                if dist[new_h][new_w] <= d + 1:
                    continue
                dist[new_h][new_w] = d + 1
                que.append((new_h, new_w))

    ans = dist[d_h][d_w]
    if ans == INF:
        print(-1)
    else:
        print(ans)


main()

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
from heapq import heapify, heappush, heappop
import numpy as np
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
from scipy.special import comb
import copy
import networkx as nx
sys.setrecursionlimit(10**6)

# lis_of_lis = [[] for _ in range(N)]


def zz():
    return list(map(int, sys.stdin.readline().split()))


def z():
    return int(sys.stdin.readline())


def S():
    return sys.stdin.readline()[:-1]


def C(line):
    return [sys.stdin.readline() for _ in range(line)]


@njit
def main():
    H, W = zz()

    c_h, c_w = zz()
    d_h, d_w = zz()
    board = []
    c_h -= 1
    c_w -= 1
    d_h -= 1
    d_w -= 1
    for i in range(H):
        tmp = S()
        board.append(tmp)

    que = deque([(c_h, c_w)])
    INF = 1e9
    dist = [[INF]*W for _ in range(H)]
    dist[c_h][c_w] = 0
    while que:
        # print(que)
        tmp = que.popleft()
        h, w = tmp
        d = dist[h][w]
        for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            new_h = h + dy
            new_w = w + dx
            if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                continue
            if board[new_h][new_w] == '#':
                continue
            if dist[new_h][new_w] <= d:
                continue
            dist[new_h][new_w] = d
            que.appendleft((new_h, new_w))
        # 魔法
        for m_dy in range(-2, 3):
            for m_dx in range(-2, 3):
                new_h = h + m_dy
                new_w = w + m_dx
                if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                    continue
                if board[new_h][new_w] == '#':
                    continue
                if dist[new_h][new_w] <= d + 1:
                    continue
                dist[new_h][new_w] = d + 1
                que.append((new_h, new_w))

    ans = dist[d_h][d_w]
    if ans == INF:
        print(-1)
    else:
        print(ans)


main()

Submission status: Runtime Error

Solution code:
import sys
from collections import deque

def input(): return sys.stdin.readline().strip()

icase=0
if icase==0:
    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=[[] for i in range(h)]
    for i in range(h):
        s[i]=input()
        
ij=[(1,0),(-1,0),(0,1),(0,-1)]
wpij=[(1,1),(-1,-1),(-1,1),(1,-1),
      (2,-2),(2,-1),(2,0),(2,1),(2,2),
      (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),
      (1,2),(0,2),(-1,2),(1,-2),(0,-2),(-1,-2)]

hh=[i for i in range(h)]
ww=[i for i in range(w)]

g=[[[] for i in range(w)] for i in range(h)]
gg=[[[] for i in range(w)] for i in range(h)]
wpg2=[[0]*w for i in range(h)]
wpg=[]

for i in hh:
    for j in ww:
        g[i][j]=[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]==".")]
        wpg2[i][j]=max([ 1 for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]=="#")])

for i in hh:
    for j in ww:
        if wpg2[i][j]==1:
            wpg.append((i,j))
                
for i,j in wpg:
    for ii,jj in wpij:
         if 0<=i+ii and i+ii<h and 0<=j+jj \
            and j+jj<w and s[i+ii][j+jj]==".":
                gg[i][j].append((i+ii,j+jj))        

q=deque([(ch,cw)])
qq=deque()
parent=[[-1]*w for i in range(h)]
parent[ch][cw]=0
dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0
while True:
    while q:
#        print("q1:",q)
        hi,wi = q.popleft()
        if len(gg[hi][wi])>0:
            qq.append((hi,wi))
        for hj,wj in g[hi][wi]:
            if parent[hj][wj] !=-1:
                continue
            else:
                parent[hj][wj]=(hi,wi)
                dist[hj][wj]=dist[hi][wi]+1
                q.append((hj,wj))
                if hj==dh and wj==dw:
                    print(dist[dh][dw]//(10**7))   
                    sys.exit()

    while qq:
        hi,wi = qq.popleft()
        for hj,wj in gg[hi][wi]:
            if parent[hj][wj]!=-1:
                continue
            parent[hj][wj]=(hi,wi)
            dist[hj][wj]=dist[hi][wi]+10**7
            q.append((hj,wj))
            if hj==dh and wj==dw:
                print(dist[dh][dw]//(10**7))   
                sys.exit()

    if len(q)==0:
        break
print(-1)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
import queue
    
def BFS(c,t,Num):
    q = queue.Queue()
    q.put(c)
    
    while not q.empty(): 
        n = q.get()
        if t[n[0] + 1][n[1]] != -1 and t[n[0] + 1][n[1]] == 9999 :
            q.put([n[0] + 1, n[1]])
            t[n[0] + 1][n[1]] = Num
    
        if t[n[0]][n[1] + 1] != -1 and t[n[0]][n[1] + 1] == 9999:
            q.put([n[0], n[1] + 1])
            t[n[0]][n[1] + 1] = Num
        
        if t[n[0] - 1][n[1]] != -1 and t[n[0] - 1][n[1]] == 9999:
            q.put([n[0] - 1, n[1] ])
            t[n[0] - 1][ n[1] ] = Num

        if t[n[0]][n[1] - 1] != -1 and t[n[0]][n[1] - 1] == 9999:
            q.put([n[0],n[1] - 1])
            t[n[0]][n[1] - 1] = Num  


def SearchNum(t, Num):
    q = queue.Queue()
    
    for i in range(H + 4):
        for j in range(W + 4):
            if t[i][j] == Num:
                q.put([i,j])    
        
    return q

def Warp(c,t,Num):
    for i in range(c[0]-2,c[0]+3):
        for j in range(c[1]-2,c[1]+3):
            if t[i][j] == 9999:
                t[i][j] = Num
    
H, W =int(input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = np.array([list(map(int,input().split())) for l in range(W)] ,dtype = object)

C[0] -= 1
C[1] -= 1
D[0] -= 1
D[1] -= 1

T = np.full([H + 4,W + 4],-1)

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)
count = 0
while True:
    q_warp = SearchNum(T,count)
    count += 1
    while not q_warp.empty():
        n = q_warp.get()
        Warp([n[0],n[1]],T,count)
        
    q_BFS = SearchNum(T,count)
    while not q_BFS.empty():
        n = q_BFS.get()
        BFS(n,T,count)
        
    if count > 1000:
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break
    

if T[D[0] + 2][D[1] + 2] != 9999:
    print(T[D[0] + 2][D[1] + 2])
else:
    print(-1)

Submission status: Runtime Error

Solution code:
import numpy as np
import queue
   
def BFS(c,t,Num):
    q = queue.Queue()
    q.put(c)
    
    while not q.empty(): 
        n = q.get()
        if t[n[0] + 1][n[1]] != -1 and t[n[0] + 1][n[1]] == 9999 :
            q.put([n[0] + 1, n[1]])
            t[n[0] + 1][n[1]] = Num
    
        if t[n[0]][n[1] + 1] != -1 and t[n[0]][n[1] + 1] == 9999:
            q.put([n[0], n[1] + 1])
            t[n[0]][n[1] + 1] = Num
        
        if t[n[0] - 1][n[1]] != -1 and t[n[0] - 1][n[1]] == 9999:
            q.put([n[0] - 1, n[1] ])
            t[n[0] - 1][ n[1] ] = Num
 
        if t[n[0]][n[1] - 1] != -1 and t[n[0]][n[1] - 1] == 9999:
            q.put([n[0],n[1] - 1])
            t[n[0]][n[1] - 1] = Num  
 
 
def SearchNum(t, Num):
    q = queue.Queue()
    
    for i in range(H + 4):
        for j in range(W + 4):
            if t[i][j] == Num:
                q.put([i,j])    
        
    return q
 
def Warp(c,t,Num):
    for i in range(c[0]-2,c[0]+3):
        for j in range(c[1]-2,c[1]+3):
            if t[i][j] == 9999:
                t[i][j] = Num
    
    
 
H, W =int(input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = np.array([list(map(int,input().split())) for l in range(W)])
 
C[0] -= 1
C[1] -= 1
D[0] -= 1
D[1] -= 1
 
T = np.full([H + 4,W + 4],-1)
 
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)
count = 0
while True:
    q_warp = SearchNum(T,count)
    count += 1
    while not q_warp.empty():
        n = q_warp.get()
        Warp([n[0],n[1]],T,count)
        
    q_BFS = SearchNum(T,count)
    while not q_BFS.empty():
        n = q_BFS.get()
        BFS(n,T,count)
        
    if count > 1000:
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break
 
if T[D[0] + 2][D[1] + 2] != 9999:
    print(T[D[0] + 2][D[1] + 2])
else:
    print(-1)

Submission status: Runtime Error

Solution code:
import numpy as np
import queue
   
def BFS(c,t,Num):
    q = queue.Queue()
    q.put(c)
    
    while not q.empty(): 
        n = q.get()
        if t[n[0] + 1][n[1]] != -1 and t[n[0] + 1][n[1]] == 9999 :
            q.put([n[0] + 1, n[1]])
            t[n[0] + 1][n[1]] = Num
    
        if t[n[0]][n[1] + 1] != -1 and t[n[0]][n[1] + 1] == 9999:
            q.put([n[0], n[1] + 1])
            t[n[0]][n[1] + 1] = Num
        
        if t[n[0] - 1][n[1]] != -1 and t[n[0] - 1][n[1]] == 9999:
            q.put([n[0] - 1, n[1] ])
            t[n[0] - 1][ n[1] ] = Num

        if t[n[0]][n[1] - 1] != -1 and t[n[0]][n[1] - 1] == 9999:
            q.put([n[0],n[1] - 1])
            t[n[0]][n[1] - 1] = Num  


def SearchNum(t, Num):
    q = queue.Queue()
    
    for i in range(H + 4):
        for j in range(W + 4):
            if t[i][j] == Num:
                q.put([i,j])    
        
    return q

def Warp(c,t,Num):
    for i in range(c[0]-2,c[0]+3):
        for j in range(c[1]-2,c[1]+3):
            if t[i][j] == 9999:
                t[i][j] = Num
    
    

H, W =int(input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = np.array([list(map(int,input().split())) for l in range(W)])

C[0] -= 1
C[1] -= 1
D[0] -= 1
D[1] -= 1

T = np.full([H + 4,W + 4],-1)

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)
count = 0
while True:
    q_warp = SearchNum(T,count)
    count += 1
    while not q_warp.empty():
        n = q_warp.get()
        Warp([n[0],n[1]],T,count)
        
    q_BFS = SearchNum(T,count)
    while not q_BFS.empty():
        n = q_BFS.get()
        BFS(n,T,count)
        
    if count > 1000:
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break

if T[D[0] + 2][D[1] + 2] != 9999:
    print(T[D[0] + 2][D[1] + 2])
else:
    print(-1)

Submission status: Runtime Error

Solution code:
import numpy as np
import queue
"""
'#'　:壁
'.'　:道
"""



    
def BFS(c,t,Num):
    q = queue.Queue()
    q.put(c)
    
    while not q.empty(): 
        n = q.get()
        if t[n[0] + 1][n[1]] != -1 and t[n[0] + 1][n[1]] == 999 :
            q.put([n[0] + 1, n[1]])
            t[n[0] + 1][n[1]] = Num
    
        if t[n[0]][n[1] + 1] != -1 and t[n[0]][n[1] + 1] == 999:
            q.put([n[0], n[1] + 1])
            t[n[0]][n[1] + 1] = Num
        
        if t[n[0] - 1][n[1]] != -1 and t[n[0] - 1][n[1]] == 999:
            q.put([n[0] - 1, n[1] ])
            t[n[0] - 1][ n[1] ] = Num

        if t[n[0]][n[1] - 1] != -1 and t[n[0]][n[1] - 1] == 999:
            q.put([n[0],n[1] - 1])
            t[n[0]][n[1] - 1] = Num  


def SearchNum(t, Num):
    q = queue.Queue()
    
    for i in range(H + 4):
        for j in range(W + 4):
            if t[i][j] == Num:
                q.put([i,j])    
        
    return q

def Warp(c,t,Num):
    for i in range(c[0]-2,c[0]+3):
        for j in range(c[1]-2,c[1]+3):
            if t[i][j] == 999:
                t[i][j] = Num
    
    

H, W =int(input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = np.array([list(map(int,input().split())) for l in range(W)])
"""
H,W = 4,4
C = [1,1]
D = [4,4]
S = np.array(
    [['.','.','#','.'],
     ['.','.','#','.'],
     ['.','#','.','.'],
     ['.','#','.','.']
     ]      
    )
"""

C[0] -= 1
C[1] -= 1
D[0] -= 1
D[1] -= 1

T = np.full([H + 4,W + 4],-1)


UnsearchedNum = 999



for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)
count = 0
while True:
    q_warp = SearchNum(T,count)
    if q_warp.empty():
        break
    count += 1
    while not q_warp.empty():
        n = q_warp.get()
        Warp([n[0],n[1]],T,count)
        
    q_BFS = SearchNum(T,count)
    while not q_BFS.empty():
        n = q_BFS.get()
        BFS(n,T,count)
        
    if T[D[0] + 2][D[1] + 2] != 999:
        break
if T[D[0] + 2][D[1] + 2] != 999:
    print(T[D[0] + 2][D[1] + 2])
else:
    print(-1)

Submission status: Runtime Error

Solution code:
direct_bool = {'left': False, 'right': False, 'up': False, 'down': False, 'counter': False}
counter = 0

def is_walkable(Ch, CW,direct_bool):
    for k in direct_bool.keys():
        direct_bool[k] = False
    if S[Ch - 1][Cw] != '#':
        direct_bool['up'] = True
    if S[Ch + 1][Cw] != '#':
        direct_bool['down'] = True
    if S[Ch][Cw - 1] != '#':
        direct_bool['left'] = True
    if S[Ch][Cw + 1] != '#':
        direct_bool['right'] = True
        
def choose_way(Ch, Cw, Dh, Dw, H, W, direct_bool):
    minimum = abs(Dh - Ch) + abs(Dw - Cw)
    next = -1, -1
    if direct_bool['up']:
        if abs(Dh - Ch + 1) + abs(Dw - Cw) < minimum:
            minimum = abs(Dh - Ch + 1) + abs(Dw - Cw)
            next = Ch - 1, Cw
    if direct_bool['down']:
        if abs(Dh - Ch - 1) + abs(Dw - Cw) < minimum:
            minimum = abs(Dh - Ch - 1) + abs(Dw - Cw)
            next = Ch + 1, Cw
    if direct_bool['left']:
        if abs(Dw - Cw + 1) + abs(Dh - Ch) < minimum:
            minimum = abs(Dh - Ch) + abs(Dw - Cw + 1)
            next = Cw - 1, Ch
    if direct_bool['right']:
        if abs(Dw - Cw - 1) + abs(Dw - Ch) < minimum:
            minimum = abs(Dh - Ch) + abs(Dw - Cw - 1)
            next = Cw + 1, Ch
            
    if not True in direct_bool.values() or next[0] == -1:
    #     ワープ
        for h in range(Ch - 2, Ch + 3):
            for w in range(Cw - 2, Cw + 3):
                if h <= 0 or w <= 0 or h > H or w > W:
                    continue
                if minimum > (abs(Dh - h) + abs(Dw - w)):
                    if S[h][w] != '#':
                        minimum = (abs(Dh - h) + abs(Dw - w))
                        direct_bool['counter'] = True
                        next = h, w
    return next
H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
S = []
for i in range(H):
    S.append(input())
S = list(map(lambda x: '#' + x + '#', S))
S.insert(0, '#' * 2 *W)
S.append('#' * 2 * W)
while True:
    is_walkable(Ch, Cw,direct_bool)
    Ch, Cw = choose_way(Ch, Cw, Dh, Dw, H, W, direct_bool)
    if Ch == -1 or Cw == -1:
        flag = False
        break
    if direct_bool['counter']:
        counter += 1
        
    if Ch == Dh and Cw == Dw:
        flag = True
        break
if flag:
    print(counter)
else:
    print(-1)

Submission status: Runtime Error

Solution code:
direct_bool = {'left': False, 'right': False, 'up': False, 'down': False, 'counter': False}
counter = 0

def is_walkable(Ch, CW,direct_bool):
    for k in direct_bool.keys():
        direct_bool[k] = False
    if S[Ch - 1][Cw] != '#':
        direct_bool['up'] = True
    if S[Ch + 1][Cw] != '#':
        direct_bool['down'] = True
    if S[Ch][Cw - 1] != '#':
        direct_bool['left'] = True
    if S[Ch][Cw + 1] != '#':
        direct_bool['right'] = True
        
def choose_way(Ch, Cw, Dh, Dw, H, W, direct_bool):
    minimum = abs(Dh - Ch) + abs(Dw - Cw)
    next = -1, -1
    if direct_bool['up']:
        if abs(Dh - Ch + 1) + abs(Dw - Cw) < minimum:
            minimum = abs(Dh - Ch + 1) + abs(Dw - Cw)
            next = Ch - 1, Cw
    if direct_bool['down']:
        if abs(Dh - Ch - 1) + abs(Dw - Cw) < minimum:
            minimum = abs(Dh - Ch - 1) + abs(Dw - Cw)
            next = Ch + 1, Cw
    if direct_bool['left']:
        if abs(Dw - Cw + 1) + abs(Dh - Ch) < minimum:
            minimum = abs(Dh - Ch) + abs(Dw - Cw + 1)
            next = Cw - 1, Ch
    if direct_bool['right']:
        if abs(Dw - Cw - 1) + abs(Dw - Ch) < minimum:
            minimum = abs(Dh - Ch) + abs(Dw - Cw - 1)
            next = Cw + 1, Ch
            
    if not True in direct_bool.values() or next[0] == -1:
    #     ワープ
        for h in range(Ch - 2, Ch + 3):
            for w in range(Cw - 2, Cw + 3):
                if h <= 0 or w <= 0 or h > H or w > W:
                    continue
                if minimum > (abs(Dh - h) + abs(Dw - w)):
                    if S[h][w] != '#':
                        minimum = (abs(Dh - h) + abs(Dw - w))
                        direct_bool['counter'] = True
                        next = h, w
    return next
H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
S = []
for i in range(H):
    S.append(input())
S = list(map(lambda x: '#' + x + '#', S))
S.insert(0, '#' * 2 *W)
S.append('#' * 2 * W)
print(S)
while True:
    is_walkable(Ch, Cw,direct_bool)
    Ch, Cw = choose_way(Ch, Cw, Dh, Dw, H, W, direct_bool)
    if Ch == -1 or Cw == -1:
        flag = False
        break
    if direct_bool['counter']:
        counter += 1
        
    if Ch == Dh and Cw == Dw:
        flag = True
        break
if flag:
    print(counter)
else:
    print(-1)

Submission status: Runtime Error

Solution code:
import sys
input =  sys.stdin.readline

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
from collections import deque

grid =  ''
grid +=  '#' * (W+4) * 2
for h in range(H):
  S = str(input())
  grid += '#' * 2 + S + '#' * 2
grid +=  '#' * (W+4) * 2

D = [(-1, 0), (1, 0), (0, -1), (0, 1)]

Ch, Cw, Dh, Dw = Ch+1, Cw+1, Dh+1, Dw+1
usedss = [[0] * (W + 4) for _ in  range(H+4)]
      
for x in range(H+4):
  for y in range(W+4):
    if grid[x*(W+4)+y] == '#':
      usedss[x][y] = 1
      
VS = set([(Ch, Cw)])
new_VS = set([(Ch, Cw)])
usedss[Ch][Cw] = 1
      
ans = 0
while True:
  while VS:
      VS2  = set()
      for x, y in VS:
        for dx, dy in D:
          x_ = x + dx
          y_ = y + dy
          if usedss[x_][y_] == 1:
            continue
          VS2.add((x_,y_))
          new_VS.add((x_, y_))
          usedss[x_][y_] = 1
      VS = VS2
      #print(VS)
      
  if usedss[Dh][Dw]:
    print(ans)
    break
    
  if not new_VS:
    print(-1)
    break
    
  VS = set()
  for x, y in new_VS:
    for dx in range(-2, 3):
      for dy in range(-2, 3):
        x_ = x + dx
        y_ = y + dy
        if usedss[x_][y_]  == 1:
          continue
        VS.add((x_, y_))
        usedss[x_][y_] = 1
        
  ans += 1
  new_VS = set(VS)