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:
    from collections import deque

    H, W = map(int, input().split())
    ch, cw = map(lambda x: int(x)-1, input().split())
    dh, dw = map(lambda x: int(x)-1, input().split())
    S = [list(input()) for _ in range(H)]
    dist = [[-1] * W for _ in range(H)]

    q = deque()
    q.append((0, ch, cw))
    while q:
        c, h, w = q.popleft()
        if dist[h][w] >= 0:
            continue
        dist[h][w] = c
        for hh in range(-2, 3):
            for ww in range(-2, 3):
                if 0 <= h+hh < H and 0 <= w+ww < W and S[h+hh][w+ww] == "." and dist[h+hh][w+ww] < 0:
                    if (hh, ww) in ((0,1), (1,0), (-1,0), (0,-1)):
                        q.appendleft((c, h+hh, w+ww)) # 徒歩は前に追加
                    else:
                        q.append((c+1, h+hh, w+ww)) # ワープは後ろに追加

    print(dist[dh][dw])

Submission status: Runtime Error

Solution code:
h, w = map(int,input())
ch, dh =  map(int,input())
cw, dw =  map(int,input())
mp = [None]+[[None]+[c for c in input()] for _ in h]

d = deque((ch,cw))
mp[ch][cw]=0

cost = 0

def mass11(_h, _w):
    l = []
    for i in (-1,1):
        for j in (-1,1):
            side_h, side_w = _h+i, _w+j
            if side_h>0 and side_h<h and side_w>0 and side_w<w:
            l.append((side_h, side_w))
    return l 

def mass55(_h, _w):
    l = []
    for i in range(5):
        for j in range(5):
            side_h, side_w = _h+i-2, _w+j-2
            if side_h>0 and side_h<h and side_w>0 and side_w<w:
            l.append((side_h, side_w))
    return l 


while not len(d) ==0:
    _h, _w = d.popleft()
    center = mp[_h][_w]
    for side_h, side_w in mass11(_h, _w):
        side = mp[side_h][side_w]
        if not side == '#' and not side == mp[_h][_w]:
            mp[side_h][side_w]=mp[_h][_w]
            d.appendleft((side_h, side_w))
    for side_h, side_w in mass55(_h, _w):
        side = mp[side_h][side_w]
        if mp[_h][_w] == '.':
            mp[side_h][side_w]=mp[_h][_w]+1
            d.append((side_h, side_w))

if mp[dh][dw] =='.':
    print(-1)
else:
    print(mp[dh][dw])

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())
s=[]
ch-=1
cw-=1
dh-=1
dw-=1

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

d=[[10**10 for i in range(w)] for j in range(h)]
d=list(d)
dx=[1,0,-1,0]
dy=[0,1,0,-1]
ddx=[-2,-2,-2,-2,-2,-1,-1,-1,-1,-1, 0, 0,0,0,0, 1, 1,1,1,1, 2, 2,2,2,2]
ddy=[-2,-1, 0, 1, 2,-2,-1, 0, 1, 2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2]
que=deque([[ch,cw]])
while que:
    p=que.popleft()
    for i in range(4):
        if i<=3:
            nx=p[0]+dx[i]
            ny=p[1]+dy[i]           
            if nx>=0 and ny>=0 and nx<h and ny<w and s[ny][nx]!="#" and d[ny][nx]>d[p[1]][p[0]]:
                d[ny][nx]=d[p[1]][p[0]]
                que.appendleft([nx,ny])
    for i in range(len(ddx)):
        nx=p[0]+ddx[i]
        ny=p[1]+ddy[i]
        if nx>=0 and ny>=0 and nx<h and ny<w and s[ny][nx]!="#" and d[ny][nx]>d[p[1]][p[0]]+1:
            d[ny][nx]=d[p[1]][p[0]]+1
            que.append([nx,ny])

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

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
Ch,Cw = map(int,input().split())
Dh,Dw = map(int,input().split())
S = [list(input()) for i in range(H)]
 
res_S = [[-1]*W for i in range(H)]
dx = [1,-1,0,0]
ddx = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]
dy = [0,0,1,-1]
ddy = [-2,-2,-2,-2,-2,-1,-1,-1,-1,0,0,1,1,1,1,2,2,2,2,2]
count = 0
 
que = [(Ch,Cw)]
que_warp =[(Ch,Cw)]
res_S[Ch-1][Cw-1] = 0
 
while (que or que_warp):
    while (que):
      	que_warp.append(que[0])
        for i in range(4):
            nx = int(que[0][0]+dx[i])
            ny = int(que[0][1]+dy[i])
            if (1<=nx<=H) and (1<=ny<=W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1]=count
                    que.append((nx,ny))
        que.pop(0)
 
    count += 1
 
    while(que_warp):
        for i in range(len(ddx)):
            nx = int(que_warp[0][0] + ddx[i])
            ny = int(que_warp[0][1] + ddy[i])
            if (1 <= nx <= H) and (1 <= ny <= W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1] = count
                    que.append((nx, ny))
        que_warp.pop(0)
 
print (res_S[Dh-1][Dw-1])

Submission status: Runtime Error

Solution code:
import queue
 
dx = [-1,0,1,0]
dy = [0,-1,0,1]
 
def bfs(ch,cw):
    q = [[] for _ in range(5000)]
    
    S[ch][cw] = 0
    q[S[ch][cw]].append([ch,cw])
    
    counter = 0
    
    while True:
        if not q[counter]:
          counter += 1
          if not q[counter]:
              break
        p = q[counter].pop()
        
        if p[0]==dh and p[1]==dw:
            break
        
        for i in range(4):
            next_p = [p[0]+dx[i],p[1]+dy[i]]
            if next_p[0]<0 or next_p[1]<0 or next_p[0]>=h or next_p[1]>=w:
                continue
            if S[next_p[0]][next_p[1]] > S[p[0]][p[1]]:
                S[next_p[0]][next_p[1]] = S[p[0]][p[1]]
                q[counter].append(next_p)
                
                
        for i in range(-2,3):
            for j in range(-2,3):
                if (i == 0 and j == 0) or (i==-1 and j==0)or(i==1 and j==0)or(i==0 and j==-1)or (i==0 and j==1):
                    continue
                next_p = [p[0]+i,p[1]+j]
                if next_p[0]<0 or next_p[1]<0 or next_p[0]>=h or next_p[1]>=w:
                    continue
                if S[next_p[0]][next_p[1]] > S[p[0]][p[1]]+1:
                    S[next_p[0]][next_p[1]] = S[p[0]][p[1]]+1
                    q[counter+1].append(next_p)
                    
            
    return 
        
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 = [list(input()) for _ in range(h)]
 
for i in range(h):
    for j in range(w):
        if S[i][j] == '.':
            S[i][j] = float('inf')
        else:
            S[i][j] = -1
 
 
bfs(ch,cw)
if S[dh][dw] != float('inf'):
    print(S[dh][dw])
else:
    print(-1)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
ch = ch - 1
cw = cw - 1
dh = dh - 1
dw = dw - 1

S = []
nextIndex = 0
requiredWarps=[]
indexes = [[-1 for j in range(W)] for i in range(H)]
warpjudgeindexes=[[-1 for j in range(W)] for i in range(H)]
for i in range(H):
    S.append(input())

def DFS(i,j):
    for a in range(4):
        if a == 0:
            if i+1<H and indexes[i+1][j] == -1 and S[i+1][j]==".":
                indexes[i + 1][j] = indexes[i][j]
                DFS(i+1,j)
        elif a == 1:
            if i>0 and indexes[i-1][j] == -1 and S[i-1][j]==".":
                indexes[i -1][j] = indexes[i][j]
                DFS(i-1,j)
                
        elif a == 2:
            if j+1<W and indexes[i][j+1] == -1 and S[i][j+1]==".":
                indexes[i][j+1] = indexes[i][j]
                DFS(i,j+1)
            
        elif a == 3:
            if j>0 and indexes[i][j-1] == -1 and S[i][j-1]==".":
                indexes[i][j-1] = indexes[i][j]
                DFS(i, j - 1)

def WarpDFS(i, j):
    warp(i,j)
    for a in range(4):
        if a == 0:
            if i+1<H and warpjudgeindexes[i+1][j] == -1 and S[i+1][j]==".":
                warpjudgeindexes[i + 1][j] = warpjudgeindexes[i][j]
                WarpDFS(i+1,j)
        elif a == 1:
            if i>0 and warpjudgeindexes[i-1][j] == -1 and S[i-1][j]==".":
                warpjudgeindexes[i -1][j] = warpjudgeindexes[i][j]
                WarpDFS(i-1,j)
                
        elif a == 2:
            if j+1<W and warpjudgeindexes[i][j+1] == -1 and S[i][j+1]==".":
                warpjudgeindexes[i][j+1] = warpjudgeindexes[i][j]
                WarpDFS(i,j+1)
            
        elif a == 3:
            if j>0 and warpjudgeindexes[i][j-1] == -1 and S[i][j-1]==".":
                warpjudgeindexes[i][j-1] = warpjudgeindexes[i][j]
                WarpDFS(i, j - 1)


def warp(a,b):
    for i in range(5):
        for j in range(5):
            u = a + i - 2
            v = b + j - 2
            if u < 0 or u >= H or v < 0 or v >= W:
                continue
            if indexes[u][v] == -1 and S[u][v] == ".":
                global nextIndex
                indexes[u][v] = nextIndex
                warpjudgeindexes[u][v]=nextIndex
                requiredWarps.append(requiredWarps[indexes[a][b]] + 1)                
                nextIndex+=1
                oneareaSearch(u, v)
            elif requiredWarps[indexes[u][v]] > requiredWarps[indexes[a][b]] + 1 and S[u][v] == ".":
                requiredWarps[indexes[u][v]]=requiredWarps[indexes[a][b]] + 1
                
def oneareaSearch(i, j):
    DFS(i, j)
    WarpDFS(i,j)

requiredWarps.append(0)
nextIndex += 1
indexes[ch][cw] = 0
warpjudgeindexes[ch][cw]=0
oneareaSearch(ch, cw)

if indexes[dh][dw] == -1:
    print("-1")
else:   
    print(requiredWarps[indexes[dh][dw]])

Submission status: Runtime Error

Solution code:
import sys
from io import StringIO
import unittest
import os
from collections import deque
import itertools

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


class UnionFind:
    def __init__(self, n):
        """
        コンストラクタ
        :要素数 n:
        """
        self.n = n
        # 添字x: 値yとすると・・
        #   root以外の場合： 要素xは集合yに所属する。
        #   rootの場合　　　： 集合xの要素数はy個である。(負数で保持する)
        self.parents = [-1] * n

    def getroot(self, x):
        """
        データが属するグループのID(と考えて良いはず)を取得する。
        :調査するグループ x:
        """
        # 値が負数 = ルートに到達したので、ルート木の番号を返す。
        if self.parents[x] < 0:
            return x
        else:
            # 値が正数 = ルートに到達していない場合、さらに親の情報を確認する。
            # 下の行は経路圧縮の処理。
            self.parents[x] = self.getroot(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        """
        2つのデータが属するグループを結合する。
        :結合するデータ(1つ目) x:
        :結合するデータ(2つ目) y:
        """
        # 既に同じ集合に存在するなら何もせず終了。
        x = self.getroot(x)
        y = self.getroot(y)
        if x == y:
            return

        # 集合を結合する。
        # ※ここ、「要素数の大きい集合に、少ない集合を結合」しているが、こうすることで以後の「処理量を削減」するテクニックである。
        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        """
        指定したグループに属するデータの数を返す。
        :調査グループ x:
        """
        # 添え字[root]には、要素数が負数で格納されている。そのため、取得する際は-反転する。
        return -self.parents[self.getroot(x)]

    def is_same(self, x, y):
        return self.getroot(x) == self.getroot(y)

    def members(self, x):
        """
        指定したグループに属するデータの一覧を返す。size()と比較して速度が圧倒的に遅いので注意。
        :調査グループ x:
        """
        root = self.getroot(x)
        return [i for i in range(self.n) if self.getroot(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


h = 0


def getpoint(point):
    global h
    ans = 0
    return (h - 1) * point[0] + point[1]


# 実装を行う関数
def resolve(test_def_name=""):
    global h
    h, w = map(int, input().split())

    start = list(map(int, input().split()))
    gorl = list(map(int, input().split()))

    work_maze = [list(input()) for i in range(h)]

    h += 1
    w += 1

    # ブロックで囲む
    maze = [["#" for _ in range(w)]]
    for line in work_maze:
        maze.append(["#"] + line + ["#"])
    maze.append([["#" for _ in range(w)]])

    # スタート地点の候補を選定する
    start_list = []
    for i in range(1, h):
        for j in range(1, w):
            # 自分が壁なら対象外
            if maze[i][j] == "#":
                continue
            start_list.append([i, j])

    # 集合の分類(-1：未調査)
    ed_list = [[-1 for i in range(w)] for j in range(h)]

    # UnionFindにて集合を明確にする。
    uf = UnionFind(h * w)

    que = deque()
    que.extend(start_list)

    # スタート地点の候補数だけ、BFSを行う(今回の問題固有で必要なループ)
    # BFS開始
    while len(que) is not 0:
        now = que.pop()

        # 各方向に集合が存在するか確認
        for move_h, move_w in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
            # 処理対象の座標
            target = [now[0] + move_h, now[1] + move_w]

            # 処理対象のチェック
            # 外なら何もしない
            if not 1 <= target[0] < h or not 1 <= target[1] < w:
                continue

            # 処理済みなら何もしない
            if ed_list[target[0]][target[1]] != -1:
                continue

            # 壁なら何もしない
            if maze[target[0]][target[1]] == "#":
                continue

            ed_list[target[0]][target[1]] = 1
            uf.union(getpoint(now), getpoint(target))

    # 探索処理
    move_list = [[] for i in range(h * w)]

    # 移動できるか確認
    que.extend(start_list)

    # BFS開始
    while len(que) is not 0:
        now = que.pop()

        # 各方向に集合が存在するか確認
        for i, j in [(-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2), (-1, -2), (-1, -1), (-1, 0), (-1, 1), (-1, 2),
                     (1, -2), (1, -1), (1, 0), (1, 1), (1, 2), (2, -2), (2, -1), (2, 0), (2, 1), (2, 2)]:
            # 処理対象の座標
            target = [now[0] + i, now[1] + j]

            if not 1 <= target[0] < h or not 1 <= target[1] < w:
                continue

            if maze[target[0]][target[1]] == "#":
                continue

            if uf.is_same(getpoint(now), getpoint(target)):
                continue

            move_list[uf.getroot(getpoint(now))].append(uf.getroot(getpoint(target)))

    moved_list = [-1 for a in range(h * w + 1)]
    move_list = [set(a) for a in move_list]

    que.append(uf.getroot(getpoint(start)))
    while len(que) is not 0:
        now = que.pop()
        movetarget = move_list[now]

        for aaa in movetarget:

            # 距離が設定済みなら何もしない
            if not moved_list[aaa] == -1:
                continue

            # キューに追加
            que.appendleft(aaa)

            # 最短距離を設定
            moved_list[aaa] = moved_list[now] + 1

    if uf.is_same(getpoint(start), getpoint(gorl)):
        print(0)
        return

    if moved_list[uf.getroot(getpoint(gorl))] == -1:
        print(-1)
        return

    print(moved_list[uf.getroot(getpoint(gorl))] + 1)

    # テストクラス


class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """4 4
1 1
4 4
..#.
..#.
.#..
.#.."""
        output = """1"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """4 4
1 4
4 1
.##.
####
####
.##."""
        output = """-1"""
        self.assertIO(test_input, output)

    def test_input_3(self):
        test_input = """4 4
2 2
3 3
....
....
....
...."""
        output = """0"""
        self.assertIO(test_input, output)

    def test_input_4(self):
        test_input = """4 5
1 2
2 5
#.###
####.
#..##
#..##"""
        output = """2"""
        self.assertIO(test_input, output)

    # 自作テストパターン
    def test_original(self):
        pass


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Runtime Error

Solution code:
import queue
from numba import njit, b1, i4, i8, f8
h, w = map(int, input().split())
c = list(map(int, input().split()))
d = list(map(int, input().split()))
ans = float('inf')
q = queue.Queue()
q.put([c[0], c[1], 0])

route = [['#']*(w+2)]
for i in range(h):
    route += [list('#'+input()+'#')]
route += [['#']*(w+2)]

@njit((b1[:, :], i8, i8, i8, i8), cache=True)
def cal(q, ans):
    while not q.empty():
        now = q.get()
        if route[now[0]][now[1]] == '.':
            route[now[0]][now[1]] = '#'
        if now[0] == d[0] and now[1] == d[1]:
            ans = min(ans, now[2])
        if route[now[0]+1][now[1]] != '#':
            q.put([now[0]+1, now[1], now[2]])
        if route[now[0]-1][now[1]] != '#':
            q.put([now[0]-1, now[1], now[2]])
        if route[now[0]][now[1]+1] != '#':
            q.put([now[0], now[1]+1, now[2]])
        if route[now[0]][now[1]-1] != '#':
            q.put([now[0], now[1]-1, now[2]])
        for i in range(-2, 3):
            for j in range(-2, 3):
                if 0 <= now[0]+i <= h+1 and 0 <= now[1]+j <= w+1:
                    if route[now[0]+i][now[1]+j] != '#':
                        q.put([now[0]+i, now[1]+j, now[2]+1])
    return ans
ans = cal(q, ans)
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
ch = ch - 1
cw = cw - 1
dh = dh - 1
dw = dw - 1

S = []
nextIndex = 0
requiredWarps=[]
indexes = [[-1 for j in range(W)] for i in range(H)]
warpjudgeindexes=[[-1 for j in range(W)] for i in range(H)]
for i in range(H):
    S.append(input())

def DFS(i,j):
    for a in range(4):
        if a == 0:
            if i+1<H and indexes[i+1][j] == -1 and S[i+1][j]==".":
                indexes[i + 1][j] = indexes[i][j]
                DFS(i+1,j)
        elif a == 1:
            if i>0 and indexes[i-1][j] == -1 and S[i-1][j]==".":
                indexes[i -1][j] = indexes[i][j]
                DFS(i-1,j)
                
        elif a == 2:
            if j+1<W and indexes[i][j+1] == -1 and S[i][j+1]==".":
                indexes[i][j+1] = indexes[i][j]
                DFS(i,j+1)
            
        elif a == 3:
            if j>0 and indexes[i][j-1] == -1 and S[i][j-1]==".":
                indexes[i][j-1] = indexes[i][j]
                DFS(i, j - 1)

def WarpDFS(i, j):
    warp(i,j)
    for a in range(4):
        if a == 0:
            if i+1<H and warpjudgeindexes[i+1][j] == -1 and S[i+1][j]==".":
                warpjudgeindexes[i + 1][j] = warpjudgeindexes[i][j]
                WarpDFS(i+1,j)
        elif a == 1:
            if i>0 and warpjudgeindexes[i-1][j] == -1 and S[i-1][j]==".":
                warpjudgeindexes[i -1][j] = warpjudgeindexes[i][j]
                WarpDFS(i-1,j)
                
        elif a == 2:
            if j+1<W and warpjudgeindexes[i][j+1] == -1 and S[i][j+1]==".":
                warpjudgeindexes[i][j+1] = warpjudgeindexes[i][j]
                WarpDFS(i,j+1)
            
        elif a == 3:
            if j>0 and warpjudgeindexes[i][j-1] == -1 and S[i][j-1]==".":
                warpjudgeindexes[i][j-1] = warpjudgeindexes[i][j]
                WarpDFS(i, j - 1)


def warp(a,b):
    for i in range(5):
        for j in range(5):
            u = a + i - 2
            v = b + j - 2
            if u < 0 or u >= H or v < 0 or v >= W:
                continue
            if (indexes[u][v] == -1 or requiredWarps[indexes[u][v]]>requiredWarps[indexes[a][b]]+1)and S[u][v] == ".":
                global nextIndex
                indexes[u][v] = nextIndex
                warpjudgeindexes[u][v]=nextIndex
                requiredWarps.append(requiredWarps[indexes[a][b]] + 1)                
                nextIndex+=1
                oneareaSearch(u,v)
                
def oneareaSearch(i, j):
    DFS(i, j)
    WarpDFS(i,j)

requiredWarps.append(0)
nextIndex += 1
indexes[ch][cw] = 0
warpjudgeindexes[ch][cw]=0
oneareaSearch(ch, cw)

if indexes[dh][dw] == -1:
    print("-1")
else:   
    print(requiredWarps[indexes[dh][dw]])

Submission status: Runtime Error

Solution code:
import queue
import numba
h, w = map(int, input().split())
c = list(map(int, input().split()))
d = list(map(int, input().split()))
ans = float('inf')
q = queue.Queue()
q.put([c[0], c[1], 0])

route = [['#']*(w+2)]
for i in range(h):
    route += [list('#'+input()+'#')]
route += [['#']*(w+2)]

@jit
def cal(q, ans):
    while not q.empty():
        now = q.get()
        if route[now[0]][now[1]] == '.':
            route[now[0]][now[1]] = '#'
        if now[0] == d[0] and now[1] == d[1]:
            ans = min(ans, now[2])
        if route[now[0]+1][now[1]] != '#':
            q.put([now[0]+1, now[1], now[2]])
        if route[now[0]-1][now[1]] != '#':
            q.put([now[0]-1, now[1], now[2]])
        if route[now[0]][now[1]+1] != '#':
            q.put([now[0], now[1]+1, now[2]])
        if route[now[0]][now[1]-1] != '#':
            q.put([now[0], now[1]-1, now[2]])
        for i in range(-2, 3):
            for j in range(-2, 3):
                if 0 <= now[0]+i <= h+1 and 0 <= now[1]+j <= w+1:
                    if route[now[0]+i][now[1]+j] != '#':
                        q.put([now[0]+i, now[1]+j, now[2]+1])
    return ans
ans = cal(q, ans)
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
Ch,Cw = map(int,input().split())
Dh,Dw = map(int,input().split())
S = [list(input()) for i in range(H)]
 
res_S = [[-1]*W for i in range(H)]
dx = [1,-1,0,0]
ddx = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]
dy = [0,0,1,-1]
ddy = [-2,-2,-2,-2,-2,-1,-1,-1,-1,0,0,1,1,1,1,2,2,2,2,2]
count = 0
 
que = [(Ch,Cw)]
que_warp =[(Ch,Cw)]
res_S[Ch-1][Cw-1] = 0
 
while (que or que_warp):
    while (que):
        if count > 0:
            que_warp.append(que[0])
        for i in range(4):
            nx = int(que[0][0]+dx[i])
            ny = int(que[0][1]+dy[i])
            if (1<=nx<=H) and (1<=ny<=W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1]=count
                    que.append((nx,ny))
                    que_warp.append((nx,ny))
        que.pop(0)
 
    count += 1
 
    while(que_warp):
        for i in range(len(ddx)):
            nx = int(que_warp[0][0] + ddx[i])
            ny = int(que_warp[0][1] + ddy[i])
            if (1 <= nx <= H) and (1 <= ny <= W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1] = count
                    que.append((nx, ny))
        que_warp.pop(0)
 
print (res_S[Dh-1][Dw-1])
H,W = map(int,input().split())
Ch,Cw = map(int,input().split())
Dh,Dw = map(int,input().split())
S = [list(input()) for i in range(H)]
 
res_S = [[-1]*W for i in range(H)]
dx = [1,-1,0,0]
ddx = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]
dy = [0,0,1,-1]
ddy = [-2,-2,-2,-2,-2,-1,-1,-1,-1,0,0,1,1,1,1,2,2,2,2,2]
count = 0
 
que = [(Ch,Cw)]
que_warp =[(Ch,Cw)]
res_S[Ch-1][Cw-1] = 0
 
while (que or que_warp):
    while (que):
      	que_warp.append(que[0])
        for i in range(4):
            nx = int(que[0][0]+dx[i])
            ny = int(que[0][1]+dy[i])
            if (1<=nx<=H) and (1<=ny<=W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1]=count
                    que.append((nx,ny))
                    que_warp.append((nx,ny))
        que.pop(0)
 
    count += 1
 
    while(que_warp):
        for i in range(len(ddx)):
            nx = int(que_warp[0][0] + ddx[i])
            ny = int(que_warp[0][1] + ddy[i])
            if (1 <= nx <= H) and (1 <= ny <= W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1] = count
                    que.append((nx, ny))
        que_warp.pop(0)
 
print (res_S[Dh-1][Dw-1])

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
from collections import deque

h, w = map(int, input().split())
ch, cw = map(int, input().split())
gh, gw = map(int, input().split())

s = []
for i in range(h):
   s.append(input().rstrip('\n'))

INF = 10 ** 10
d = [INF] * (h*w)

stack = deque([[ch-1, cw-1, 0]])
stack_append = stack.append
stack_popleft = stack.popleft

nex = []
for i in range(-2, 3):
    for j in range(-2, 3):
        if (i, j) in [(-1,0),(1,0),(0,-1),(0,1),(0,0)]:
            continue
        else:
            nex.append((i,j))

while stack:
    curh, curw, cnt = stack_popleft()
    f = 0
    if d[curh * w + curw] <= cnt:
        continue
    else:
        d[curh * w + curw] = cnt
    for dh, dw in ((-1,0), (1,0), (0,1), (0,-1)):
        nh = curh + dh
        nw = curw + dw
        if nh >= 0 and nh < h and nw >= 0 and nw < w and s[nh][nw] == '.' and d[nh * w + nw] > cnt:
            stack_append([nh, nw, cnt])
        if s[nh][nw] == '#':
            f = 1
    if f:
        for dh, dw in nex:
            nh = curh + dh
            nw = curw + dw
            if nh >= 0 and nh < h and nw >= 0 and nw < w and s[nh][nw] == '.' and  d[nh * w + nw] > cnt:
                stack_append([nh, nw, cnt+1])

# for item in d:
#     print(item)
gh -= 1
gw -= 1

if d[gh*w + gw] == INF:
    print(-1)
else:
    print(d[gh*w + gw])

Submission status: Runtime Error

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(100000)

H, W = map(int, input().split())
si, sj = map(lambda x: int(x) - 1, input().split())
gi, gj = map(lambda x: int(x) - 1, input().split())

maze = [input() for i in range(H)]
reached = [[-1] * W for i in range(H)]

direction = [(-1, 0), (0, -1), (0, 1), (1, 0)]
reached_que = deque([[si, sj]])


def bfs(si, sj):
    que = deque([[si, sj]])
    if reached[si][sj] != -1:
        return
    while que:
        h, w = que.popleft()
        for a, b in direction:
            next_h = h + a
            next_w = w + b
            if next_h > H - 1 or next_w > W - 1 or next_h < 0 or next_w < 0:
                continue
            if maze[next_h][next_w] == '#':
                continue
            if reached[next_h][next_w] != -1:
                continue
            que.append([next_h, next_w])
            reached[next_h][next_w] = reached[h][w] + 1
            reached_que.append([next_h, next_w])


hankei_5 = [
    [-2, -2],
    [-2, -1],
    [-2, 0],
    [-2, 1],
    [-2, 2],
    [-1, -2],
    [-1, -1],
    [-1, 0],
    [-1, 1],
    [-1, 2],
    [0, -2],
    [0, -1],
    [0, 1],
    [0, 2],
    [1, -2],
    [1, -1],
    [1, 0],
    [1, 1],
    [1, 2],
    [2, -2],
    [2, -1],
    [2, 0],
    [2, 1],
    [2, 2]
]

ans = -1


def bfs2(si, sj):
    kouho = []
    for i, j in hankei_5:
        next_h = si + i
        next_w = sj + j
        if next_h > H - 1 or next_w > W - 1 or next_h < 0 or next_w < 0:
            continue
        if maze[next_h][next_w] == '.' and reached[next_h][next_w] == -1:
            kouho.append([next_h, next_w])
    return kouho


def check(si, sj, ans):
    bfs(si, sj)
    if reached[gi][gj] == -1:
        kouho = []
        for r in reached_que:
            a = bfs2(r[0], r[1])
            kouho = a + kouho
        if len(kouho) == 0:
            print(ans)
            exit(0)
        else:
            for k in kouho:
                check(k[0], k[1], ans + 1)
    else:
        ans += 1
        print(ans)
        exit(0)


check(si, sj, -1)

Submission status: Runtime Error

Solution code:
import sys
from collections import deque
H, W = map(int, input().split())
c = [int(i) + 1 for i in input().split()]
d = [int(i) + 1 for i in input().split()]

s = []
s.append('#'*(W+4))
s.append('#'*(W+4))
for i in range(H):
    a = input()
    s.append('##' + a + '##')
s.append('#'*(W+4))
s.append('#'*(W+4))

q = deque([]) # 探索開始点
qq = deque([])
q.append((c[0], c[1], 0))
visited = [[False for __ in range(W+4)] for _ in range(H+4)]

while q:
    xx, yy, kaisuu = q.popleft()
    if visited[xx][yy] == True:
        continue
    qq.append((xx, yy, kaisuu))
    ls = deque()
    while qq:
        x, y, kaisuu = qq.pop()
        visited[x][y] = True
        ls.append((x, y, kaisuu))
        if x == d[0] and y == d[1]:
            print(kaisuu)
            sys.exit()
        if s[x+1][y] == '.' and visited[x+1][y] == False:
            qq.append((x+1, y, kaisuu))
        if s[x-1][y] == '.' and visited[x-1][y] == False:
            qq.append((x-1, y, kaisuu))
        if s[x][y+1] == '.' and visited[x][y+1] == False:
            qq.append((x, y+1, kaisuu))
        if s[x][y-1] == '.' and visited[x][y-1] == False:
            qq.append((x, y-1, kaisuu))
    for u in ls:
        a, b, e = u
        s = set()
        for i in range(-2, 3):
            for j in range(-2, 3):
                if i == 0 and j == 0:
                    continue
                if abs(i) == 1 and abs(j) == 1:
                    continue
                if s[a+i][b+j] == '.' and visited[a+i][b+j] == False and (a+i, b+j, e+1) not in s:
                    q.append((a+i, b+j, e+1))
                    s.add((a+i, b+j, e+1))
print(-1)