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:
import sys
sys.setrecursionlimit(10**6)
from collections import deque
from copy import deepcopy
def main():
    movey = (0, -1, 0, 1)
    movex = (1, 0, -1, 0)
    warpy = (-2, -2, -2, -2, -2, -1, -1, -1, -1,  0, 0,  1,  1, 1, 1, 2, 2, 2, 2, 2)
    warpx = (-2, -1,  0,  1,  2, -2, -1,  1,  2, -2, 2, -2, -1, 1, 2, -2, -1, 0, 1, 2)

    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
    dummy = ['#'] * (w + 4)
    maze = list()
    maze.append(dummy)
    maze.append(dummy)
    for _ in range(h):
        row = ['#'] + ['#'] + list(input()) + ['#'] + ['#']
        maze.append(row)
    maze.append(dummy)
    maze.append(dummy)
    maze[ch][cw] = 0
    #maze[dh][dw] = 'g'

    next_nodes = deque()
    next_nodes.append((ch, cw))
    next2_nodes = deque()
    #cnt = 0
    while next_nodes:
        while next_nodes:
            nextn = next_nodes.popleft()
            nextny = nextn[0]
            nextnx = nextn[1]
            curg = maze[nextny][nextnx]
            flag = False
            for j1 in range(4):
                ny = nextny + movey[j1]
                nx = nextnx + movex[j1]
                if maze[ny][nx] == '.':
                    maze[ny][nx] = curg
                    next2_nodes.append((ny, nx))
                elif maze[ny][nx] == '#':
                    flag = True
                elif maze[ny][nx] > curg:
                    maze[ny][nx] = curg
                    #next2_nodes.append((ny, nx))
            if flag:
                for j1 in range(20):
                    ny = nextny + warpy[j1]
                    nx = nextnx + warpx[j1]
                    nextg = maze[ny][nx]
                    if nextg == '.':
                        next2_nodes.append((ny, nx))
                        maze[ny][nx] = curg + 1
                    elif nextg == '#':
                        pass
                    elif nextg > curg + 1:
                        maze[ny][nx] = curg + 1
                        #next2_nodes.append((ny, nx))
        next_nodes = deepcopy(next2_nodes)
        next2_nodes = deque()
    g = maze[dh][dw]
    if g == '.':
        print(-1)
    else:
        print(g)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
inf = 10 ** 9
from collections import deque
def bfs(sx, sy):
    cost = [[inf] * w for i in range(h)]
    d = ((0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1))
    cost[sx - 1][sy - 1] = 0
    q = deque()
    q.append((sx - 1, sy - 1))
    
    while q:
        s, t = q.popleft()
        for dx, dy in d:
            nx = s + dx
            ny = t + dy
            
            if not(0 <= nx < h and 0 <= ny < w):continue
            if cost[nx][ny] <= cost[s][t]:continue
            if (dx + dy)%2 == 0:
                if c[nx][ny] == '.' and cost[nx][ny] > cost[s][t] + 1:
                    cost[nx][ny] = cost[s][t] + 1
                    if (nx, ny) == (dh - 1, dw - 1):
                        q.append((nx, ny))

                next_d = ((dx, 0), (0, dy), (dx, dy))
                for ddx, ddy in next_d:
                    nnx = nx + ddx
                    nny = ny + ddy
                    if not(0 <= nnx < h and 0 <= nny < w):continue
                    if c[nnx][nny] == '#':continue
                    if cost[nnx][nny] <= cost[s][t] + 1:continue
                    cost[nnx][nny] = cost[s][t] + 1
                    
                    if (nnx, nny) == (dh - 1, dw - 1):continue
                    q.append((nnx, nny))
                continue
                    
            elif c[nx][ny] == '.' and (dx + dy)%2 != 0:
                cost[nx][ny] = min(cost[nx][ny], cost[s][t])
                
            elif c[nx][ny] == '#' and (dx + dy)%2 != 0:
                nx += dx
                ny += dy
                if not(0 <= nx < h and 0 <= ny < w):continue
                if c[nx][ny] == '#':continue
                if cost[nx][ny] <= cost[s][t] + 1:continue
                cost[nx][ny] = cost[s][t] + 1
                
            if (nx, ny) == (dh - 1, dw - 1):continue
            q.append((nx, ny))

    return cost
        
h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())
c = [list(input()) for _ in range(h)]

res = bfs(ch, cw)
if res[dh - 1][dw - 1] == inf:print(-1)
else:print(res[dh - 1][dw - 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())

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

def isOK(h,w):
    if 0<=h<H and 0<=w<W:
        if L[h][w]!="#":
            return True
        
    return False


DX=[1,0,-1,0]
DY=[0,1,0,-1]

que=deque([])
count=0
que.append((ch-1,cw-1, 0))
cost=[[-1]*W for _ in range(H)]
cost[ch-1][cw-1]=0
lis=[(ch-1,cw-1)]
while que:
    while que:
        t=que.popleft()
        x,y,now=t
        for i in range(4):
            dx,dy=DX[i],DY[i]
            nx=x+dx
            ny=y+dy
            if isOK(nx,ny):
                if cost[nx][ny]==-1:
                    cost[nx][ny]=now
                    que.appendleft((nx,ny,now))
                    lis.append((nx,ny))
    for t in lis:
        x,y=t
        for dx in range(-2,3):
            for dy in range(-2,3):
                if dx==0 and dy==0:
                    continue
                nx=x+dx
                ny=y+dy
                if isOK(nx,ny):
                    if cost[nx][ny]==-1:
                        cost[nx][ny]=count+1
                        que.append((nx,ny,count+1))
    count+=1
    lis=[]

print(cost[dh-1][dw-1])

#print(cost)

Submission status: Wrong Answer

Solution code:
from collections import deque
HW = input().split()
H, W = int(HW[0]), int(HW[1])
C = input().split()
Ch, Cw = int(C[0]), int(C[1])
D = input().split()
Dh, Dw = int(D[0]), int(D[1])
route = []
for h in range(H):
    route.append(input())


visited = [[False]*W for x in range(H)]
kouho = deque()
kouho.append([Ch-1, Cw-1])
warpkouho = deque()

def check_walk(a, b):
    if 0 <= a <= H-1 and 0 <= b <= W-1: 
        if visited[a][b] == False and route[a][b] == ".":
            kouho.append([a, b])
def check_warp(a, b, cwarp):
    if 0 <= a <= H-1 and 0 <= b <= W-1:
        if visited[a][b] == False and route[a][b] == ".":
            warpkouho.append([a, b, cwarp+1])

def wizard():
    warp = 1
    while True:
        if len(kouho) != 0:
            tmp = kouho.popleft()
        elif len(warpkouho) != 0:
            tmp = warpkouho.popleft()
            warp = tmp[2]
        else:
            break
        h = tmp[0]
        w = tmp[1]
        if visited[h][w] == False:
            visited[h][w] = warp
            check_walk(h-1, w)
            check_walk(h+1, w)
            check_walk(h, w-1)
            check_walk(h, w+1)
            for n in range(5):
                for m in range(5):
                    check_warp(h-2+n, w-2+m, warp)
    if h == Dh-1 and w == Dw-1:
      	print(visited[h][w]-1)
      	return
    print(-1)
wizard()

Submission status: Wrong Answer

Solution code:
from collections import deque
HW = input().split()
H, W = int(HW[0]), int(HW[1])
C = input().split()
Ch, Cw = int(C[0]), int(C[1])
D = input().split()
Dh, Dw = int(D[0]), int(D[1])
route = []
for h in range(H):
    route.append(input())


visited = [[False]*W for x in range(H)]
kouho = deque()
kouho.append([Ch-1, Cw-1])
warpkouho = deque()

def check_walk(a, b):
    if 0 <= a <= H-1 and 0 <= b <= W-1: 
        if visited[a][b] == False and route[a][b] == ".":
            kouho.append([a, b])
def check_warp(a, b, cwarp):
    if 0 <= a <= H-1 and 0 <= b <= W-1:
        if visited[a][b] == False and route[a][b] == ".":
            warpkouho.append([a, b, cwarp+1])

def wizard():
    warp = 1
    while True:
        if len(kouho) != 0:
            tmp = kouho.pop()
        elif len(warpkouho) != 0:
            tmp = warpkouho.pop()
            warp = tmp[2]
        else:
            break
        h = tmp[0]
        w = tmp[1]
        if visited[h][w] == False:
            visited[h][w] = warp
            check_walk(h-1, w)
            check_walk(h+1, w)
            check_walk(h, w-1)
            check_walk(h, w+1)
            for n in range(5):
                for m in range(5):
                    check_warp(h-2+n, w-2+m, warp)
    if h == Dh-1 and w == Dw-1:
      	print(visited[h][w]-1)
      	return
    print(-1)
wizard()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
import itertools as it
from collections import deque

def main(H, W, Ch, Cw, Dh, Dw, S):

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

    # pick root 
    root = (Ch, Cw)
    
    # flag
    empty_while = True
    count = 0

    """DFS"""
    def DFS(node, block=set([])):
        def pick_next(node):
            h,w = node
            assert S[h][w]
            for next_h, next_w in [
                (h+1, w), # down
                (h, w+1), # right
                (h, w-1), # left
                (h-1, w)  # up
            ]:
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        # mark root as traversed
        visited[node[0]][node[1]] = True
        block.add(node)

        # if there is a node to go to 
        while pick_next(node):
            node = pick_next(node)
            if node:
                # mark node as traversed
                h, w = node
                visited[h][w] = True
                block.add(node)

                # go to next node
                DFS(node, block)
        
        return frozenset(block)

    """BFS"""
    def BFS(node):
        def pick_next(node):
            h,w = node
            r = range(-2, 3)
            for h_offset, w_offset in it.product(r,r):
                next_h = h + h_offset
                next_w = w + w_offset
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        queue = deque([])
        levels = {}

        start = DFS(node)
        queue.append(start)  
        levels[start] = 0

        while queue:
            block = queue.popleft()
            
            if visited[Dh][Dw]:
                    return levels[block]

            for node in block:

                if pick_next(node):
                    node = pick_next(node)

                    # add node to queue
                    next_block = DFS(node, block=set([]))
                    queue.append(next_block)
                    levels[next_block] = levels[block] + 1


        return -1 

    node = root
    count = BFS(node)    
        
    print(count)
    pass

if __name__ == '__main__':
    H, W = list(map(int, input().split()))
    Ch, Cw = list(map(int, input().split()))
    Dh, Dw = list(map(int, input().split()))
    S = [[False for _ in range(W)] for __ in range(H)]

    for h in range(H):
        S_row = input()
        for w, s in enumerate(S_row):
            if s=='.':
                S[h][w] = True
            else:
                S[h][w] = False

    Ch -= 1
    Cw -= 1
    Dh -= 1
    Dw -= 1

    main(H, W, Ch, Cw, Dh, Dw, S)

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

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

def isOK(h,w):
    if 0<=h<H and 0<=w<W:
        if L[h][w]==".":
            return True
    return False

que=deque([(ch-1,cw-1,0)])
DX=[0,1,0,-1]
DY=[1,0,-1,0]
lis=[(ch-1,cw-1)]
cost=[[-1]*W for _ in range(H)]
cost[ch-1][cw-1]=0
count=0
while que:
    while que:
        t=que.popleft()
        x,y,now=t
        for i in range(4):
            dx=DX[i]
            dy=DY[i]
            nx=x+dx
            ny=y+dy
            if isOK(nx,ny):
                if cost[nx][ny]==-1:
                    cost[nx][ny]=now
                    que.append((nx,ny,now))
                    lis.append((nx,ny))
    for t in lis:
        x,y=t
        for dx in range(-2,3):
            for dy in range(-2,3):
                if abs(dx)+abs(dy)<=1:
                    continue
                nx=x+dx
                ny=y+dy
                if isOK(nx,ny):
                    if cost[nx][ny]==-1:
                        cost[nx][ny]=count+1
                        que.append((nx,ny,count+1))
    count+=1
    lis=[]


print(cost[dh-1][dw-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
HW = input().split()
H, W = int(HW[0]), int(HW[1])
C = input().split()
Ch, Cw = int(C[0]), int(C[1])
D = input().split()
Dh, Dw = int(D[0]), int(D[1])
route = []
for h in range(H):
    route.append(input())


visited = [[False]*W for x in range(H)]
kouho = deque()
kouho.append([Ch-1, Cw-1])
warpkouho = deque()

def check_walk(a, b):
    if 0 <= a <= H-1 and 0 <= b <= W-1: 
        if visited[a][b] == False and route[a][b] == ".":
            kouho.append([a, b])
def check_warp(a, b, cwarp):
    if 0 <= a <= H-1 and 0 <= b <= W-1:
        if visited[a][b] == False and route[a][b] == ".":
            warpkouho.append([a, b, cwarp+1])

def wizard():
    warp = 1
    while True:
        if len(kouho) != 0:
            tmp = kouho.pop()
        elif len(warpkouho) != 0:
            tmp = warpkouho.pop()
            warp = tmp[2]
        else:
            break
        h = tmp[0]
        w = tmp[1]
        if visited[h][w] == False:
            visited[h][w] = warp
            check_walk(h-1, w)
            check_walk(h+1, w)
            check_walk(h, w-1)
            check_walk(h, w+1)
            for n in range(5):
                for m in range(5):
                    check_warp(h-2+n, w-2+m, warp)
        if h == Dh-1 and w == Dw-1:
            print(visited[h][w]-1)
            return
    print(-1)
wizard()

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

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

def isOK(h,w):
    if 0<=h<H and 0<=w<W:
        if L[h][w]==".":
            return True
    return False

que=deque([(ch-1,cw-1,0)])
DX=[0,1,0,-1]
DY=[1,0,-1,0]
lis=[(ch-1,cw-1)]
cost=[[-1]*W for _ in range(H)]
cost[ch-1][cw-1]=0
count=0
while que:
    while que:
        t=que.popleft()
        x,y,now=t
        for i in range(4):
            dx=DX[i]
            dy=DY[i]
            nx=x+dx
            ny=y+dy
            if isOK(nx,ny):
                if cost[nx][ny]==-1:
                    cost[nx][ny]=now
                    que.append((nx,ny,now))
                    lis.append((nx,ny))
    for t in lis:
        x,y=t
        for dx in range(-2,3):
            for dy in range(-2,3):
                if dx==0 and dy==0:
                    continue
                nx=x+dx
                ny=y+dy
                if isOK(nx,ny):
                    if cost[nx][ny]==-1:
                        cost[nx][ny]=count+1
                        que.append((nx,ny,count+1))
    count+=1
    lis=[]


print(cost[dh-1][dw-1])

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
import itertools as it

def main(H, W, Ch, Cw, Dh, Dw, S):

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

    # pick root 
    root = (Ch, Cw)
    
    # flag
    empty_while = True
    count = 0

    """DFS"""
    def DFS(node, block=set([])):
        def pick_next(node):
            h,w = node
            assert S[h][w]
            for next_h, next_w in [
                (h+1, w), # down
                (h, w+1), # right
                (h, w-1), # left
                (h-1, w)  # up
            ]:
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        # mark root as traversed
        visited[node[0]][node[1]] = True
        block.add(node)

        # if there is a node to go to 
        while pick_next(node):
            node = pick_next(node)
            if node:
                # mark node as traversed
                h, w = node
                visited[h][w] = True
                block.add(node)

                # go to next node
                DFS(node, block)
        
        return block

    """BFS"""
    def BFS(node):
        def pick_next(node):
            h,w = node
            r = range(-2, 3)
            for h_offset, w_offset in it.product(r,r):
                next_h = h + h_offset
                next_w = w + w_offset
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        depth = 0
        queue = []
        queue.append(DFS(node))  

        while queue:
            block = queue.pop(0)
            if visited[Dh][Dw]:
                    return depth

            for node in block:

                if pick_next(node):
                    node = pick_next(node)

                    # add node to queue
                    queue.append(DFS(node, block=set([])))

            if len(queue) == 1:
                depth += 1
        return -1 

    node = root
    count = BFS(node)    
        
    print(count)
    pass

if __name__ == '__main__':
    H, W = list(map(int, input().split()))
    Ch, Cw = list(map(int, input().split()))
    Dh, Dw = list(map(int, input().split()))
    S = [[False for _ in range(W)] for __ in range(H)]

    for h in range(H):
        S_row = input()
        for w, s in enumerate(S_row):
            if s=='.':
                S[h][w] = True
            else:
                S[h][w] = False

    Ch -= 1
    Cw -= 1
    Dh -= 1
    Dw -= 1

    main(H, W, Ch, Cw, Dh, Dw, S)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**6)

def main():
    movey = (0, -1, 0, 1)
    movex = (1, 0, -1, 0)
    warpy = (-2, -2, -2, -2, -2, -1, -1, -1, -1,  0, 0,  1,  1, 1, 1, 2, 2, 2, 2, 2)
    warpx = (-2, -1,  0,  1,  2, -2, -1,  1,  2, -2, 2, -2, -1, 1, 2, -2, -1, 0, 1, 2)

    def warp(cury2, curx2):
        curg2 = maze[cury2][curx2]
        nexts2 = []
        for j1 in range(20):
            nexty2 = cury2 + warpy[j1]
            nextx2 = curx2 + warpx[j1]
            nextg2 = maze[nexty2][nextx2]
            if nextg2 == 'g':
                print(curg2 + 1)
                sys.exit()
            elif nextg2 == '.':
                maze[nexty2][nextx2] = curg2 + 1
                nexts2.append((nexty2, nextx2))
            elif type(nextg2) == int and nextg2 > curg2 + 1:
                maze[nexty2][nextx2] = curg2 + 1
                nexts2.append((nexty2, nextx2))
        return nexts2

    def dfs1(cury, curx, called):
        flag = False
        curg = maze[cury][curx]
        next_koho = []
        for i1 in range(4):
            nexty = cury + movey[i1]
            nextx = curx + movex[i1]
            nextg = maze[nexty][nextx]
            if nextg == 'g':
                print(curg)
                sys.exit()
            elif nextg == '.':
                maze[nexty][nextx] = curg
                next_koho += dfs1(nexty, nextx, True)
            elif nextg == '#':
                flag = True
            elif type(nextg) == int and nextg > curg:
                maze[nexty][nextx] = curg
                next_koho += dfs1(nexty, nextx, True)
        if called:
            if flag:
                next_koho += [(cury, curx)]
            return next_koho
        else:
            nexts = []
            if flag:
                next_koho += [(cury, curx)]
            for ne1 in next_koho:
                nexts += warp(ne1[0], ne1[1])
            if nexts:
                for ne in nexts:
                    dfs1(ne[0], ne[1], False)

    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
    dummy = ['#'] * (w + 4)
    maze = list()
    maze.append(dummy)
    maze.append(dummy)
    for _ in range(h):
        row = ['#'] + ['#'] + list(input()) + ['#'] + ['#']
        maze.append(row)
    maze.append(dummy)
    maze.append(dummy)
    maze[ch][cw] = 0
    maze[dh][dw] = 'g'
    dfs1(ch, cw, False)
    print(-1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
import itertools as it

def main(H, W, Ch, Cw, Dh, Dw, S):

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

    # pick root 
    root = (Ch, Cw)
    
    # flag
    empty_while = True
    count = 0

    """DFS"""
    def DFS(node, block=set([])):
        def pick_next(node):
            h,w = node
            assert S[h][w]
            for next_h, next_w in [
                (h+1, w), # down
                (h, w+1), # right
                (h, w-1), # left
                (h-1, w)  # up
            ]:
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        # mark root as traversed
        visited[node[0]][node[1]] = True
        block.add(node)

        # if there is a node to go to 
        while pick_next(node):
            node = pick_next(node)
            if node:
                # mark node as traversed
                h, w = node
                visited[h][w] = True
                block.add(node)

                # go to next node
                DFS(node, block)
        
        return block

    """BFS"""
    def BFS(node):
        def pick_next(node):
            h,w = node
            r = range(-2, 3)
            for h_offset, w_offset in it.product(r,r):
                next_h = h + h_offset
                next_w = w + w_offset
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        depth = 0
        queue = []
        queue.append(DFS(node))  

        while queue:
            block = queue.pop(0)
            if visited[Dh][Dw]:
                    return depth

            for node in block:

                if pick_next(node):
                    node = pick_next(node)

                    # add node to queue
                    queue.append(DFS(node, block=set([])))

            depth += 1
        return -1 

    node = root
    count = BFS(node)    
        
    print(count)
    pass

if __name__ == '__main__':
    H, W = list(map(int, input().split()))
    Ch, Cw = list(map(int, input().split()))
    Dh, Dw = list(map(int, input().split()))
    S = [[False for _ in range(W)] for __ in range(H)]

    for h in range(H):
        S_row = input()
        for w, s in enumerate(S_row):
            if s=='.':
                S[h][w] = True
            else:
                S[h][w] = False

    Ch -= 1
    Cw -= 1
    Dh -= 1
    Dw -= 1

    main(H, W, Ch, Cw, Dh, Dw, S)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
import itertools as it

def main(H, W, Ch, Cw, Dh, Dw, S):

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

    # pick root 
    root = (Ch, Cw)
    
    # flag
    empty_while = True
    count = 0

    """DFS"""
    def DFS(node, block=set([])):
        def pick_next(node):
            h,w = node
            assert S[h][w]
            for next_h, next_w in [
                (h+1, w), # down
                (h, w+1), # right
                (h, w-1), # left
                (h-1, w)  # up
            ]:
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        # mark root as traversed
        visited[node[0]][node[1]] = True
        block.add(node)

        # if there is a node to go to 
        while pick_next(node):
            node = pick_next(node)
            if node:
                # mark node as traversed
                h, w = node
                visited[h][w] = True
                block.add(node)

                # go to next node
                DFS(node, block)
        
        return block

    """BFS"""
    def BFS(node):
        def pick_next(node):
            h,w = node
            r = range(-2, 3)
            for h_offset, w_offset in it.product(r,r):
                next_h = h + h_offset
                next_w = w + w_offset
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        depth = 0
        queue = []
        queue.append(DFS(node))  

        while queue:
            block = queue.pop(0)

            for node in block:

                if visited[Dh][Dw]:
                    break

                if pick_next(node):
                    node = pick_next(node)

                    # add node to queue
                    queue.append(DFS(node, block=set([])))

                    depth += 1
        return depth 

    node = root
    count = BFS(node)    

    if not visited[Dh][Dw]:        
        print(-1)
        return 
        
    print(count)
    pass

if __name__ == '__main__':
    H, W = list(map(int, input().split()))
    Ch, Cw = list(map(int, input().split()))
    Dh, Dw = list(map(int, input().split()))
    S = [[False for _ in range(W)] for __ in range(H)]

    for h in range(H):
        S_row = input()
        for w, s in enumerate(S_row):
            if s=='.':
                S[h][w] = True
            else:
                S[h][w] = False

    Ch -= 1
    Cw -= 1
    Dh -= 1
    Dw -= 1

    main(H, W, Ch, Cw, Dh, Dw, S)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
sH, sW = map(int, input().split())
sH, sW = sH - 1, sW - 1
gH, gW = map(int, input().split())
gH, gW = gH - 1, gW - 1
graph = []
scores = []
for _ in range(H):
    graph.append(list(input()))
    scores.append([float('inf')] * W)
scores[sH][sW] = 0
q = deque()
m2_q = deque()
q.append([sW, sH])
m2_q.append([sW, sH])
dx_list = [0, 1, 0, -1]
dy_list = [1, 0, -1, 0]
while q or m2_q:
    if scores[gH][gW] != float('inf'):
        break
    # 移動aで出来る範囲をすべて探索
    while q:
        x, y = q.pop()
        for dx, dy in zip(dx_list, dy_list):
            nx, ny = x + dx, y + dy
            if nx < 0 or W <= nx or ny < 0 or H <= ny:
                continue
            if scores[ny][nx] == float('inf') and graph[ny][nx] == '.':
                scores[ny][nx] = scores[y][x]
                q.appendleft([nx, ny])
                m2_q.append([nx, ny])

    # 移動bで動けるマスをqに格納
    while m2_q:
        x, y = m2_q.pop()
        for dx in range(-2, 3):
            for dy in range(-2, 3):
                nx, ny = x + dx, y + dy
                if nx < 0 or W <= nx or ny < 0 or H <= ny or graph[ny][nx] == '#':
                    continue

                if scores[ny][nx] == float('inf'):
                    q.append([nx, ny])
                    scores[ny][nx] = scores[y][x] + 1

# print(*scores,sep='\n')
if scores[gH][gW] == float('inf'):
    print(-1)
else:
    print(scores[gH][gW])