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: Wrong Answer

Solution code:
from collections import deque

class BFS:
    def __init__(self, H, W, S, C, D):
        self.H = H
        self.W = W
        self.S = S
        # 魔法使いの場所
        self.C = C
        # 目的地
        self.D = D

        # 盤面上のセルの状態
        # -1: 未到達
        # 0 : 魔法0回で到達
        # 1 : 魔法1回で到達
        # 2 : 魔法2回で到達, and so on...
        self.board_states = [[-1] * W for i in range(H)]
        self.board_states[C[0]][C[1]] = 0
        self.queue = deque([C])
        self.remain_cells = [C]

    def is_legal_move(self, move):
        h = move[0]
        w = move[1]

        if h < 0 or h >= self.H or w < 0 or w >= self.W:
            return False
        return self.S[h][w] == "."

    def is_not_visited(self, move):
        h = move[0]
        w = move[1]
        return self.board_states[h][w] == -1

    def walk(self):
        next_queue = deque([])
        while len(self.queue) > 0:
            if len(self.queue) == 0 and len(next_queue) > 0:
                self.queue = next_queue

            move = self.queue.popleft()

            up = (move[0]-1, move[1])
            down = (move[0]+1, move[1])
            left = (move[0], move[1]-1)
            right = (move[0], move[1]+1)

            next_moves = list(filter(self.is_legal_move, [up, down, left, right]))

            for next_move in next_moves:
                if self.is_not_visited(next_move):
                    self.queue.append(next_move)
                    self.remain_cells.append(next_move)
                    self.set_boart_states(next_move, self.get_boart_states(move))

    def set_boart_states(self, move, value):
        self.board_states[move[0]][move[1]] = value

    def get_boart_states(self, move):
        return self.board_states[move[0]][move[1]]

    def print_board_states(self):
        for l in self.board_states:
            print(l)

H, W = map(int, input().split())
C_h, C_w = map(int, input().split())
C_h -= 1
C_w -= 1
D_h, D_w = map(int, input().split())
D_h -= 1
D_w -= 1

S = [ [None] * W for i in range(H) ]
for i in range(H):
    l = input()
    for j, s in enumerate(l):
        S[i][j] = s

bfs = BFS(H, W, S, (C_h, C_w), (D_h, D_w))

while (True):
    bfs.walk()
    if len(bfs.remain_cells) == 0:
        break
    
    while len(bfs.remain_cells) > 0:
        move = bfs.remain_cells.pop()
        for i in range(-2, 3):
            for j in range(-2, 3):
                next_move = (move[0]+i, move[1]+j)
                if not bfs.is_legal_move(next_move):
                    continue

                if bfs.is_not_visited(next_move):
                    bfs.queue.append(next_move)
                    bfs.set_boart_states(next_move, bfs.get_boart_states(move) + 1)
                elif (not bfs.is_not_visited(next_move)) and bfs.get_boart_states(next_move) > bfs.get_boart_states(move) + 1:
                    bfs.queue.append(next_move)
                    bfs.set_boart_states(next_move, bfs.get_boart_states(move) + 1)

print(bfs.get_boart_states((D_h, D_w)))

Submission status: Wrong Answer

Solution code:
from collections import deque

class BFS:
    def __init__(self, H, W, S, C, D):
        self.H = H
        self.W = W
        self.S = S
        # 魔法使いの場所
        self.C = C
        # 目的地
        self.D = D

        # 盤面上のセルの状態
        # -1: 未到達
        # 0 : 魔法0回で到達
        # 1 : 魔法1回で到達
        # 2 : 魔法2回で到達, and so on...
        self.board_states = [[-1] * W for i in range(H)]
        self.board_states[C[0]][C[1]] = 0
        self.queue = deque([C])
        self.remain_cells = [C]
        self.warp_count = 0

    def is_legal_move(self, move):
        h = move[0]
        w = move[1]

        if h < 0 or h >= self.H or w < 0 or w >= self.W:
            return False
        return self.S[h][w] == "."

    def is_not_visited(self, move):
        h = move[0]
        w = move[1]
        return self.board_states[h][w] == -1

    def walk(self):
        next_queue = deque([])
        while len(self.queue) > 0:
            if len(self.queue) == 0 and len(next_queue) > 0:
                self.queue = next_queue

            move = self.queue.popleft()

            up = (move[0]-1, move[1])
            down = (move[0]+1, move[1])
            left = (move[0], move[1]-1)
            right = (move[0], move[1]+1)

            next_moves = list(filter(self.is_legal_move, [up, down, left, right]))

            for next_move in next_moves:
                if self.is_not_visited(next_move):
                    self.queue.append(next_move)
                    self.remain_cells.append(next_move)
                    self.set_boart_states(next_move, self.get_boart_states(move))

    def set_boart_states(self, move, value):
        self.board_states[move[0]][move[1]] = value

    def get_boart_states(self, move):
        return self.board_states[move[0]][move[1]]

    def print_board_states(self):
        for l in self.board_states:
            print(l)

H, W = map(int, input().split())
C_h, C_w = map(int, input().split())
C_h -= 1
C_w -= 1
D_h, D_w = map(int, input().split())
D_h -= 1
D_w -= 1

S = [ [None] * W for i in range(H) ]
for i in range(H):
    l = input()
    for j, s in enumerate(l):
        S[i][j] = s

bfs = BFS(H, W, S, (C_h, C_w), (D_h, D_w))

while (True):
    bfs.walk()
    if len(bfs.remain_cells) == 0:
        break
    
    while len(bfs.remain_cells) > 0:
        move = bfs.remain_cells.pop()
        for i in range(-2, 3):
            for j in range(-2, 3):
                next_move = (move[0]+i, move[1]+j)
                if not bfs.is_legal_move(next_move):
                    continue

                if bfs.is_not_visited(next_move):
                    bfs.queue.append(next_move)
                    bfs.set_boart_states(next_move, bfs.get_boart_states(move) + 1)
                elif bfs.get_boart_states(next_move) > bfs.get_boart_states(move) + 1:
                    bfs.queue.append(next_move)
                    bfs.set_boart_states(next_move, bfs.get_boart_states(move) + 1)


print(bfs.get_boart_states((D_h, D_w)))

Submission status: Wrong Answer

Solution code:
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_=list(input())
  s.append(s_)
from collections import deque
q=deque([(ch-1,cw-1)])

used=[[-1]*w for i in range(h)]
used[ch-1][cw-1]=0

while len(q)>0:
  p=q.popleft()
  y=p[0]
  x=p[1]
  Y=(-2,-1,0,1,2)
  X=(-2,-1,0,1,2)
  for dy in Y:
    for dx in X:
      if not (dy==0 and dx==0):
        if (dy==1 and dx==0) or (dy==-1 and dx==0) or (dy==0 and dx==-1) or (dy==0 and dx==1):
          if y+dy>=0 and y+dy<h and x+dx>=0 and x+dx<w and used[y+dy][x+dx]==-1 and s[y+dy][x+dx]==".":
            q.appendleft((y+dy,x+dx))
            used[y+dy][x+dx]=used[y][x]
        else:
          print(dy,dx)
          if y+dy>=0 and y+dy<h and x+dx>=0 and x+dx<w and used[y+dy][x+dx]==-1 and s[y+dy][x+dx]==".":
            q.append((y+dy,x+dx))
            used[y+dy][x+dx]=used[y][x]+1
print(used[dh-1][dw-1])

Submission status: Wrong Answer

Solution code:
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_=list(input())
  s.append(s_)
from collections import deque
q=deque([(ch-1,cw-1)])

used=[[-1]*w for i in range(h)]
used[ch-1][cw-1]=0
while len(q)>0:
  p=q.popleft()
  y=p[0]
  x=p[1]
  Y=(-2,-1,0,1,2)
  X=(-2,-1,0,1,2)
  for dy in Y:
    for dx in X:
      if not (dy==0 and dx==0):
        if (dy==1 and dx==0) or (dy==-1 and dx==0) or(dy==0 and dx==-1) or (dy==0 and dx==1):
          
          if y+dy>=0 and y+dy<h and x+dx>=0 and x+dx<w and used[y+dy][x+dx]==-1 and s[y+dy][x+dx]==".":
            q.appendleft((y+dy,x+dx))
            used[y+dy][x+dx]=used[y][x]
        else:
          
          if y+dy>=0 and y+dy<h and x+dx>=0 and x+dx<w and used[y+dy][x+dx]==-1 and s[y+dy][x+dx]==".":
            q.append((y+dy,x+dx))
            used[y+dy][x+dx]=used[y][x]+1
print(used[dh-1][dw-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
c = tuple(int(x)+1 for x in input().split())
d = [int(x)+1 for x in input().split()]
maze = [[-1] * (W+4), [-1] * (W+4)]

for i in range(H):
    temp = []
    s0 = input()
    s0 = '11' + s0.replace('.', '0').replace('#', '1') + '11'
    for j, s in enumerate(s0):
        temp.append(-int(s))
    maze.append(temp)
maze.append([-1] * (W+4))
maze.append([-1] * (W+4))

def check55(i, j):
    cset = {(ii, jj) for ii in range(i-2, i+3) for jj in range(j-2, j+3) if maze[ii][jj]!=0}
    cset = cset - {(i-1, j), (i, j), (i+1, j), (i, j-1), (i, j+1)}
    return cset

def check(i, j, delta):
    if delta[0] != 0:
        cset = {(i+3*delta[0],jj) for jj in range(j-2, j+3)} 
    else:
        cset = {(ii, j+3*delta[1]) for ii in range(i-2, i+3)}
    return cset

#bfs

k = 1
tempbfs = deque([[c[0], c[1], k]])
flag = 0
while tempbfs:
    if flag == 1:break
    p = tempbfs.popleft()

    #dfs
    if maze[p[0]][p[1]] != 0:continue
    maze[p[0]][p[1]] = p[2]
    if p[0] == d[0] and p[1] == d[1]:
        flag = 1
        k = p[2]
        break
    temp = [(p[0], p[1])]
    dset = set()
    while temp:
        p0 = temp.pop()
        for delta in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            y = p0[0] + delta[0]
            x = p0[1] + delta[1]
            if maze[y][x] != 0: continue
            maze[y][x] = p[2]
            if y == d[0] and x == d[1]:
                flag = 1
                k = p[2]
                break
            temp.append((y, x))
            dset = dset | check(p0[0], p0[1], delta)

    if flag == 1: break
    dset = dset | check55(p[0], p[1])
    for l in dset:
        if maze[l[0]][l[1]] == 0:
            tempbfs.append([l[0], l[1], p[2]+1])

print(k - 1 if flag else -1)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
c = tuple(int(x)+1 for x in input().split())
d = [int(x)+1 for x in input().split()]
maze = [[-1] * (W+4), [-1] * (W+4)]

for i in range(H):
    temp = []
    s0 = input()
    s0 = '11' + s0.replace('.', '0').replace('#', '1') + '11'
    for j, s in enumerate(s0):
        temp.append(-int(s))
    maze.append(temp)
maze.append([-1] * (W+4))
maze.append([-1] * (W+4))

def check(i, j, delta):
    if delta[0] != 0:
        cset = {(i+3*delta[0],jj) for jj in range(j-2, j+3)} 
    else:
        cset = {(ii, j+3*delta[1]) for ii in range(i-2, i+3)}
    return cset

#bfs
dset = set()
k = 1
tempbfs = deque([[c[0], c[1], k]])
flag = 0
while tempbfs:
    if flag == 1:break
    p = tempbfs.popleft()

    #dfs
    if maze[p[0]][p[1]] != 0:continue
    maze[p[0]][p[1]] = p[2]
    if p[0] == d[0] and p[1] == d[1]:
        flag = 1
        k = p[2]
        break
    temp = [(p[0], p[1])]
    while temp and flag == 0:
        p0 = temp.pop()
        for delta in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            y = p0[0] + delta[0]
            x = p0[1] + delta[1]
            if maze[y][x] != 0: continue
            if y == d[0] and x == d[1]:
                flag = 1
                k = p[2]
                break
            maze[y][x] = p[2]
            temp.append((y, x))
            dset = dset | check(p0[0], p0[1], delta)

    if flag == 1: break
    for l in dset:
        if maze[l[0]][l[1]] == 0:
            tempbfs.append([l[0], l[1], p[2]+1])
    dset = set()
print(k - 1 if flag else -1)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
c = tuple(int(x)+1 for x in input().split())
d = [int(x)+1 for x in input().split()]
maze = [[-1] * (W+4), [-1] * (W+4)]

for i in range(H):
    temp = []
    s0 = input()
    s0 = '11' + s0.replace('.', '0').replace('#', '1') + '11'
    for j, s in enumerate(s0):
        temp.append(-int(s))
    maze.append(temp)
maze.append([-1] * (W+4))
maze.append([-1] * (W+4))

def check(i, j, delta):
    if delta[0] != 0:
        cset = {(i+3*delta[0],jj) for jj in range(j-2, j+3)} 
    else:
        cset = {(ii, j+3*delta[1]) for ii in range(i-2, i+3)}
    return cset

#bfs
dset = set()
tempbfs = deque([c])
k = 1
flag = 0
while tempbfs:
    if flag == 1:break
    p = tempbfs.popleft()

    #dfs
    if maze[p[0]][p[1]] != 0:continue
    maze[p[0]][p[1]] = k
    temp = [(p[0], p[1])]
    while temp and flag == 0:
        p0 = temp.pop()
        for delta in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            y = p0[0] + delta[0]
            x = p0[1] + delta[1]
            if maze[y][x] != 0: continue
            if y == d[0] and x == d[1]:
                flag = 1
                break
            maze[y][x] = k
            temp.append((y, x))
            dset = dset | check(p0[0], p0[1], delta)

    if flag == 1: break
    k += 1
    for l in dset:
        if maze[l[0]][l[1]] == 0:
            tempbfs.append([l[0], l[1], k])
    dset = set()
print(k - 1 if flag else -1)

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
c = list(map(int,input().split()))
d = list(map(int,input().split()))
p = []
q = [[None for i in range(w)]for i in range(h)]
r = [[] for i in range(10**6)]
for i in range(h):
    s = input()
    s = list(s)
    p.append(s)
from collections import deque
de = deque()
de.append([c[0],c[1]])
q[c[0]-1][c[1]-1] = 0
g = 0
while q[d[0]-1][d[1]-1] == None and g < 10**6-3:
    while de:
        v = de.popleft()
        r[g].append([v[0]-1,v[1]-1])
        v[0] -= 1
        v[1] -= 1
        for i in (-1,1):
            j = 0
            if 0 <= v[0]-i <= h-1:
                if 0 <= v[1]-j <= w-1:
                    if p[v[0]-i][v[1]-j] == '.' and q[v[0]-i][v[1]-j] == None:
                        q[v[0]-i][v[1]-j] = g
                        de.append([v[0]-i+1,v[1]-j+1])
        for j in (-1,1):
            i = 0
            if 0 <= v[0]-i <= h-1:
                if 0 <= v[1]-j <= w-1:
                    if p[v[0]-i][v[1]-j] == '.' and q[v[0]-i][v[1]-j] == None:
                        q[v[0]-i][v[1]-j] = g
                        de.append([v[0]-i+1,v[1]-j+1])
    g += 1
    while r[g-1]:
        v = r[g-1].pop()
        for i in range(-2,3):
            for j in range(-2,3):
                if -1 <= i <= 1 and -1 <= j <= 1:
                    continue
                else:
                    if 0 <= v[0]-i <= h-1:
                        if 0 <= v[1]-j <= w-1:
                            if p[v[0]-i][v[1]-j] == '.' and q[v[0]-i][v[1]-j] == None:
                                q[v[0]-i][v[1]-j] = g
                                de.append([v[0]-i+1,v[1]-j+1])
if q[d[0]-1][d[1]-1] == None:
    print(-1)
else:
    print(q[d[0]-1][d[1]-1])

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
c = list(map(int,input().split()))
d = list(map(int,input().split()))
p = []
q = [[None for i in range(w)]for i in range(h)]
r = [[] for i in range(10**6)]
for i in range(h):
    s = input()
    s = list(s)
    p.append(s)
from collections import deque
de = deque()
de.append([c[0],c[1]])
q[c[0]-1][c[1]-1] = 0
g = 0
while q[d[0]-1][d[1]-1] == None and g < 10**6-3:
    while de:
        v = de.popleft()
        r[g].append([v[0]-1,v[1]-1])
        v[0] -= 1
        v[1] -= 1
        for i in (-1,1):
            j = 0
            if 0 <= v[0]-i <= h-1:
                if 0 <= v[1]-j <= w-1:
                    if p[v[0]-i][v[1]-j] == '.' and q[v[0]-i][v[1]-j] == None:
                        q[v[0]-i][v[1]-j] = g
                        de.append([v[0]-i+1,v[1]-j+1])
        for j in (-1,1):
            i = 0
            if 0 <= v[0]-i <= h-1:
                if 0 <= v[1]-j <= w-1:
                    if p[v[0]-i][v[1]-j] == '.' and q[v[0]-i][v[1]-j] == None:
                        q[v[0]-i][v[1]-j] = g
                        de.append([v[0]-i+1,v[1]-j+1])
    g += 1
    while r[g-1]:
        v = r[g-1].pop()
        for i in range(-2,3):
            for j in range(-2,3):
                if -1 <= i <= 1 and -1 <= j <= 1:
                    continue
                else:
                    if 0 <= v[0]-i <= h-1:
                        if 0 <= v[1]-j <= w-1:
                            if p[v[0]-i][v[1]-j] == '.' and q[v[0]-i][v[1]-j] == None:
                                q[v[0]-i][v[1]-j] = g
                                de.append([v[0]-i+1,v[1]-j+1])
print(q)
print(q[d[0]-1][d[1]-1])

Submission status: Wrong Answer

Solution code:
import collections
h,w = map(int,input().split())
si,sj = map(int,input().split())
gi,gj = map(int,input().split())
si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
grid = []
for _ in range(h):
    grid.append(input())

q = collections.deque([(0,si,sj)])
visited = set()
visited.add((si,sj))
while q:
    mindist,i,j = q.popleft()
    if (i,j) == (gi,gj):
        print(mindist)
        break
    for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
        if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
            if (ni,nj) not in visited:
                q.appendleft((mindist,ni,nj))
                visited.add((ni,nj))
    for ni in range(i-2,i+3):
        if not (0 <= ni and ni < h): continue
        for nj in range(j-2,j+3):
            if not (0 <= nj and nj < w): continue
            if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                if (ni,nj) not in visited:
                    visited.add((ni,nj))
                    q.append((mindist+1,ni,nj))

else:
    print(-1)

Submission status: Wrong Answer

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 = [list('#'*(w+2)) for i in range(h+2)]
for i in range(h):
    a = '#' + input() + '#'
    s[i+1] = list(a)
queue = deque([[ch,cw]])
s[ch][cw] = 0
l = [[0,-1],[0,1],[-1,0],[1,0]] 
r = [[] for i in range(20)]
k = 0
for i in range(-2,3):
    for j in range(-2,3):
        if i != 0 or j != 0:
            if not [i,j] in l:
                r[k] = [i,j]
                k += 1
while queue:
    x,y = queue.popleft()
    if [x,y] != [dh,dw]:
        for n,m in l:
            new_h,new_w = x+n,y+m 
            if s[new_h][new_w] == '.':
                s[new_h][new_w] = s[x][y]
                queue.appendleft([new_h,new_w])
            elif s[new_h][new_w] != "#":
                s[new_h][new_w] = min(s[new_h][new_w],s[x][y])
            else:
                pass
        for n,m in r:
            new_h,new_w = x+n,y+m
            if new_h >= 0 and new_h <= h+1 and new_w >= 0 and new_w <= w+1:
                if s[new_h][new_w] == '.':
                    s[new_h][new_w] = s[x][y]+1
                    queue.append([new_h,new_w])
                elif s[new_h][new_w] != "#":
                    s[new_h][new_w] = min(s[new_h][new_w],s[x][y]+1)
                else:
                    pass
if s[dh][dw] != '.':
    print(s[dh][dw])
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

H, W, ch, cw, gh, gw, *S = open(0).read().split()
H, W, ch, cw, gh, gw = [int(_) - 1 for _ in [H, W, ch, cw, gh, gw]]
H += 1
W += 1

X = []
Y = []
D = []
for i in range(H * W):
    h, w = divmod(i, W)
    if S[h][w] == '#':
        continue
    for dh in range(-2, 3):
        for dw in range(-2, 3):
            if 0 <= h + dh < H and 0 <= w + dw < W and (
                    dh > 0 or
                (dh == 0 and dw > 0)) and S[h + dh][w + dw] == '.':
                X += [i]
                Y += [i + dw + W * dh]
                D += [0 if (dh, dw) in ((1, 0), (0, 1)) else 1]

Submission status: Wrong Answer

Solution code:

### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest
from collections import deque

def resolve():
    readline=sys.stdin.readline

    h,w=map(int, readline().rstrip().split())
    ch,cw=map(int, readline().rstrip().split())
    dh,dw=map(int, readline().rstrip().split())
    ch-=1
    cw-=1
    dh-=1
    dw-=1

    mp=[[None for i in range(w)] for j in range(h)]

    for i in range(h):
        ss = readline().rstrip()
        for j in range(w):
            if ss[j]=="#":
                mp[i][j] = -1

    d = deque()

    if mp[ch][cw]==None:
        mp[ch][cw]=0
        d.append((ch,cw))

    while len(d) > 0:
        wrps=set()
        y,x = d.popleft()
        for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
            ny=y+dy
            nx=x+dx
            if 0 <= ny < h and 0 <= nx < w and mp[ny][nx]==None:
                mp[ny][nx]=mp[y][x]
                d.append((ny,nx))
        for dy in range(-2,3):
            for dx in range(-2,3):
                ny=y+dy
                nx=x+dx
                if 0 <= ny < h and 0 <= nx < w:
                    wrps.add((ny,nx))
        if len(d)==0:
            for ny,nx in wrps:
                if mp[ny][nx]==None:
                    mp[ny][nx]=mp[y][x]+1
                    d.append((ny,nx))
    if mp[dh][dw] == None:
        print(-1)
    else:
        print(mp[dh][dw])    
    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Wrong Answer

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 = []

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

def main():
	H,W = i_map()

	C_h,C_w = i_map()
	D_h,D_w = i_map()

	S = []
	for i in range(0,H):
		tmp = s_input()
		tmp2 = []
		for j in range(0,W):
			tmp2.append(tmp[j])
		S.append(tmp2)

	start = [C_h-1,C_w-1]
	exit = [D_h-1,D_w-1]

	rel_matrix = [([[] for i in range(W)]) for i in range(H)]
	dir = [[-1,0],[1,0],[0,-1],[0,1]]
	for i in range(0,H):
		for j in range(0,W):
			for v_dir in dir:
				if isIn(H,W,i+v_dir[0],j+v_dir[1]):
					if(S[i][j] == '.' and S[i+v_dir[0]][j+v_dir[1]] == '.'):
						rel_matrix[i][j].append((i+v_dir[0],j+v_dir[1]))

	color = [['white' for i in range(W)] for j in range(H)]
	cost = [[-1 for i in range(W)] for j in range(H)]
	
	q =  queue.Queue()
	cost[start[0]][start[1]] = 0
	color[start[0]][start[1]]='gray'
	q.put(start)
	while(not q.empty()):
		u = q.get()
		for rel in rel_matrix[u[0]][u[1]]:
			if color[rel[0]][rel[1]] == 'white':
				cost[rel[0]][rel[1]] = 0
				color[rel[0]][rel[1]]  = 'gray'
				q.put(rel)
		color[u[0]][u[1]] = 'black'

	current_cost = 0
	while True:
		currentList = []
		for i in range(0,H):
			for j in range(0,W):
				if(cost[i][j] == current_cost):
					currentList.append((i,j))
		if(len(currentList)==0):
			break

		nextList  = []
		for kouho in currentList:
			for i in range(-2,3):
				for j in range(-2,3):
					if(kouho[0]+i >= 0 and kouho[0]+i <= H-1 and kouho[1] + j >= 0 and kouho[1] + j <= W-1):
						if(S[kouho[0]+i][kouho[1]+j]=='.' and color[kouho[0]+i][kouho[1]+j] == 'white'):
							nextList.append((kouho[0]+i,kouho[1]+j))
		nextList = set(nextList)
		for next in nextList:
			q2 = queue.Queue()
			cost[next[0]][next[1]] =current_cost+1
			color[next[0]][next[1]] = 'gray'
			q2.put((next[0],next[1]))
			while(not q2.empty):
				u = q2.get()
				for rel in rel_matrix[u[0]][u[1]]:
					if color[rel[0]][rel[1]] == 'white':
						cost[rel[0]][rel[1]] = current_cost + 1
						color[rel[0]][rel[1]]  = 'gray'
						q2.put(rel)
				color[u[0]][u[1]] = 'black'
		current_cost += 1


	print(cost[D_h-1][D_w-1])



if __name__ == '__main__':
	main()

Submission status: Wrong Answer

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 = []

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

def main():
	H,W = i_map()

	C_h,C_w = i_map()
	D_h,D_w = i_map()

	S = []
	for i in range(0,H):
		tmp = s_input()
		tmp2 = []
		for j in range(0,W):
			tmp2.append(tmp[j])
		S.append(tmp2)

	start = [C_h-1,C_w-1]
	exit = [D_h-1,D_w-1]

	rel_matrix = [([[] for i in range(W)]) for i in range(H)]
	dir = [[-1,0],[1,0],[0,-1],[0,1]]
	for i in range(0,H):
		for j in range(0,W):
			for v_dir in dir:
				if isIn(H,W,i+v_dir[0],j+v_dir[1]):
					if(S[i][j] == '.' and S[i+v_dir[0]][j+v_dir[1]] == '.'):
						rel_matrix[i][j].append((i+v_dir[0],j+v_dir[1]))

	color = [['white' for i in range(W)] for j in range(H)]
	cost = [[-1 for i in range(W)] for j in range(H)]
	
	q =  queue.Queue()
	cost[start[0]][start[1]] = 0
	color[start[0]][start[1]]='gray'
	q.put(start)
	while(not q.empty()):
		u = q.get()
		for rel in rel_matrix[u[0]][u[1]]:
			if color[rel[0]][rel[1]] == 'white':
				cost[rel[0]][rel[1]] = 0
				color[rel[0]][rel[1]]  = 'gray'
				q.put(rel)
		color[u[0]][u[1]] = 'black'

	currentList = []
	for i in range(0,H):
		for j in range(0,W):
			if(cost[i][j] == 0):
				currentList.append((i,j))

	nextList  = []
	for kouho in currentList:
		for i in range(-2,3):
			for j in range(-2,3):
				if(kouho[0]+i >= 0 and kouho[0]+i <= H-1 and kouho[1] + j >= 0 and kouho[1] + j <= W-1):
					if(S[kouho[0]+i][kouho[1]+j]=='.' and color[kouho[0]+i][kouho[1]+j] == 'white'):
						nextList.append((kouho[0]+i,kouho[1]+j))
	nextList = set(nextList)
	for next in nextList:
		q2 = queue.Queue()
		cost[next[0]][next[1]] =1
		color[next[0]][next[1]] = 'gray'
		q2.put((next[0],next[1]))
		while(not q2.empty):
			u = q2.get()
			for rel in rel_matrix[u[0]][u[1]]:
				if color[rel[0]][rel[1]] == 'white':
					cost[rel[0]][rel[1]] = 1
					color[rel[0]][rel[1]]  = 'gray'
					q2.put(rel)
			color[u[0]][u[1]] = 'black'

	print(cost[D_h-1][D_w-1])



if __name__ == '__main__':
	main()