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:
H,W = [int(a) for a in input().split()]
s = [int(a) for a in input().split()]
e = [int(a) for a in input().split()]
S = [0]*(H*W)
for h in range(H):
    tmp=input()
    for w in range(len(tmp)):
        if tmp[w]=='.':S[h*W+w]=1
#print( H,W,s,e,S,sep='\n')
walk=[[] for _ in range(H*W)]
warp=[[] for _ in range(H*W)]
#print(walk,warp,sep='\n')
for i in range(H):
    for j in range(W):
        if S[i*W+j]==0:continue
        if i==0:
            if j==0:pass
            elif j==1:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
            else:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[i*W+j-2]:
                    warp[i*W+j].append(i*W+j-2)
                    warp[i*W+j-2].append(i*W+j)
        elif i==1:
            if j==0:
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
            elif j==1:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
            else:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
                if S[i*W+j-2]:
                    warp[i*W+j].append(i*W+j-2)
                    warp[i*W+j-2].append(i*W+j)
                if S[(i-1)*W+j-2]:
                    warp[i*W+j].append((i-1)*W+j-2)
                    warp[(i-1)*W+j-2].append(i*W+j)
            if j<W-1:
                if S[(i-1)*W+j+1]:
                    warp[i*W+j].append((i-1)*W+j+1)
                    warp[(i-1)*W+j+1].append(i*W+j)
                if j<W-2:
                    if S[(i-1)*W+j+2]:
                        warp[i*W+j].append((i-1)*W+j+2)
                        warp[(i-1)*W+j+2].append(i*W+j)
        else:
            if j==0:
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-2)*W+j]:
                    warp[i*W+j].append((i-2)*W+j)
                    warp[(i-2)*W+j].append(i*W+j)
            elif j==1:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
                if S[(i-2)*W+j]:
                    warp[i*W+j].append((i-2)*W+j)
                    warp[(i-2)*W+j].append(i*W+j)
                if S[(i-2)*W+j-1]:
                    warp[i*W+j].append((i-2)*W+j-1)
                    warp[(i-2)*W+j-1].append(i*W+j)
            else:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
                if S[i*W+j-2]:
                    warp[i*W+j].append(i*W+j-2)
                    warp[i*W+j-2].append(i*W+j)
                if S[(i-1)*W+j-2]:
                    warp[i*W+j].append((i-1)*W+j-2)
                    warp[(i-1)*W+j-2].append(i*W+j)
                if S[(i-2)*W+j]:
                    warp[i*W+j].append((i-2)*W+j)
                    warp[(i-2)*W+j].append(i*W+j)
                if S[(i-2)*W+j-1]:
                    warp[i*W+j].append((i-2)*W+j-1)
                    warp[(i-2)*W+j-1].append(i*W+j)
                if S[(i-2)*W+j-2]:
                    warp[i*W+j].append((i-2)*W+j-2)
                    warp[(i-2)*W+j-2].append(i*W+j)
            if j<W-1:
                if S[(i-1)*W+j+1]:
                    warp[i*W+j].append((i-1)*W+j+1)
                    warp[(i-1)*W+j+1].append(i*W+j)
                if S[(i-2)*W+j+1]:
                    warp[i*W+j].append((i-2)*W+j+1)
                    warp[(i-2)*W+j+1].append(i*W+j)
                if j<W-2:
                    if S[(i-1)*W+j+2]:
                        warp[i*W+j].append((i-1)*W+j+2)
                        warp[(i-1)*W+j+2].append(i*W+j)
                    if S[(i-2)*W+j+2]:
                        warp[i*W+j].append((i-2)*W+j+2)
                        warp[(i-2)*W+j+2].append(i*W+j)
#print(walk)
#print(warp)
from collections import deque
done = [0]*(H*W)
waiting_walk = deque()
waiting_warp = deque()
start=(s[0]-1)*W+s[1]-1
end=(e[0]-1)*W+e[1]-1
done[start] = 1
#print(start)
cnt=0
for n in warp[start]:
    waiting_warp.append(n)
for n in walk[start]:
    waiting_walk.append(n)
    if n==end:
        waiting_walk=[]
        waiting_warp=[]
warping=0
if len(waiting_walk)==0:warping=1
found=0
while len(waiting_walk) or len(waiting_warp):
    if warping:
        #print("warping")
        for i in range(len(waiting_warp)):
            to=waiting_warp[i]
            #print(to)
            if to==end:
                found=1
                cnt+=1
                break
            if done[to]!=1:
                waiting_walk.append(to)
        if to==end:break
        warping=0
        cnt+=1
        waiting_warp.clear()
    else:
        cur_node = waiting_walk.popleft()
        if done[cur_node]!=1:
            done[cur_node]=1
            #print(cur_node)
            if cur_node==end:
                found=1
                #print("found")
                break
            for n in walk[cur_node]:
                if done[n]!=1:
                    waiting_walk.append(n)
            for n in warp[cur_node]:
                if done[n]!=1:
                    waiting_warp.append(n)
        if len(waiting_walk)==0:warping=1
if found:print(cnt)
else:print(-1)

Submission status: Wrong Answer

Solution code:
H,W = [int(a) for a in input().split()]
s = [int(a) for a in input().split()]
e = [int(a) for a in input().split()]
S = [0]*(H*W)
for h in range(H):
    tmp=input()
    for w in range(len(tmp)):
        if tmp[w]=='.':S[h*W+w]=1
print( H,W,s,e,S,sep='\n')
walk=[[] for _ in range(H*W)]
warp=[[] for _ in range(H*W)]
#print(walk,warp,sep='\n')
for i in range(H):
    for j in range(W):
        if S[i*W+j]==0:continue
        if i==0:
            if j==0:pass
            elif j==1:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
            else:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[i*W+j-2]:
                    warp[i*W+j].append(i*W+j-2)
                    warp[i*W+j-2].append(i*W+j)
        elif i==1:
            if j==0:
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
            elif j==1:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
            else:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
                if S[i*W+j-2]:
                    warp[i*W+j].append(i*W+j-2)
                    warp[i*W+j-2].append(i*W+j)
                if S[(i-1)*W+j-2]:
                    warp[i*W+j].append((i-1)*W+j-2)
                    warp[(i-1)*W+j-2].append(i*W+j)
            if j<W-1:
                if S[(i-1)*W+j+1]:
                    warp[i*W+j].append((i-1)*W+j+1)
                    warp[(i-1)*W+j+1].append(i*W+j)
                if j<W-2:
                    if S[(i-1)*W+j+2]:
                        warp[i*W+j].append((i-1)*W+j+2)
                        warp[(i-1)*W+j+2].append(i*W+j)
        else:
            if j==0:
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-2)*W+j]:
                    warp[i*W+j].append((i-2)*W+j)
                    warp[(i-2)*W+j].append(i*W+j)
            elif j==1:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
                if S[(i-2)*W+j]:
                    warp[i*W+j].append((i-2)*W+j)
                    warp[(i-2)*W+j].append(i*W+j)
                if S[(i-2)*W+j-1]:
                    warp[i*W+j].append((i-2)*W+j-1)
                    warp[(i-2)*W+j-1].append(i*W+j)
            else:
                if S[i*W+j-1]:
                    walk[i*W+j].append(i*W+j-1)
                    walk[i*W+j-1].append(i*W+j)
                if S[(i-1)*W+j]:
                    walk[i*W+j].append((i-1)*W+j)
                    walk[(i-1)*W+j].append(i*W+j)
                if S[(i-1)*W+j-1]:
                    warp[i*W+j].append((i-1)*W+j-1)
                    warp[(i-1)*W+j-1].append(i*W+j)
                if S[i*W+j-2]:
                    warp[i*W+j].append(i*W+j-2)
                    warp[i*W+j-2].append(i*W+j)
                if S[(i-1)*W+j-2]:
                    warp[i*W+j].append((i-1)*W+j-2)
                    warp[(i-1)*W+j-2].append(i*W+j)
                if S[(i-2)*W+j]:
                    warp[i*W+j].append((i-2)*W+j)
                    warp[(i-2)*W+j].append(i*W+j)
                if S[(i-2)*W+j-1]:
                    warp[i*W+j].append((i-2)*W+j-1)
                    warp[(i-2)*W+j-1].append(i*W+j)
                if S[(i-2)*W+j-2]:
                    warp[i*W+j].append((i-2)*W+j-2)
                    warp[(i-2)*W+j-2].append(i*W+j)
            if j<W-1:
                if S[(i-1)*W+j+1]:
                    warp[i*W+j].append((i-1)*W+j+1)
                    warp[(i-1)*W+j+1].append(i*W+j)
                if S[(i-2)*W+j+1]:
                    warp[i*W+j].append((i-2)*W+j+1)
                    warp[(i-2)*W+j+1].append(i*W+j)
                if j<W-2:
                    if S[(i-1)*W+j+2]:
                        warp[i*W+j].append((i-1)*W+j+2)
                        warp[(i-1)*W+j+2].append(i*W+j)
                    if S[(i-2)*W+j+2]:
                        warp[i*W+j].append((i-2)*W+j+2)
                        warp[(i-2)*W+j+2].append(i*W+j)
#print(walk)
#print(warp)
from collections import deque
done = [0]*(H*W)
waiting_walk = deque()
waiting_warp = deque()
start=(s[0]-1)*W+s[1]-1
end=(e[0]-1)*W+e[1]-1
done[start] = 1
#print(start)
cnt=0
for n in warp[start]:
    waiting_warp.append(n)
for n in walk[start]:
    waiting_walk.append(n)
    if n==end:
        waiting_walk=[]
        waiting_warp=[]
warping=0
if len(waiting_walk)==0:warping=1
found=0
while len(waiting_walk) or len(waiting_warp):
    if warping:
        #print("warping")
        for i in range(len(waiting_warp)):
            to=waiting_warp[i]
            #print(to)
            if to==end:
                found=1
                cnt+=1
                break
            if done[to]!=1:
                waiting_walk.append(to)
        if to==end:break
        warping=0
        cnt+=1
        waiting_warp.clear()
    else:
        cur_node = waiting_walk.popleft()
        if done[cur_node]!=1:
            done[cur_node]=1
            #print(cur_node)
            if cur_node==end:
                found=1
                #print("found")
                break
            for n in walk[cur_node]:
                if done[n]!=1:
                    waiting_walk.append(n)
            for n in warp[cur_node]:
                if done[n]!=1:
                    waiting_warp.append(n)
        if len(waiting_walk)==0:warping=1
if found:print(cnt)
else:print(-1)

Submission status: Wrong Answer

Solution code:
import math
from itertools import product
from collections import deque

h, w = map(int, input().split())
c = tuple(map(lambda x: int(x) - 1, input().split()))
d = tuple(map(lambda x: int(x) - 1, input().split()))
S = {}
roads = set()
for i in range(h):
    s = input()
    for j in range(w):
        S[i, j] = s[j]
        if s[j] == '.':
            roads.add((i, j))

index = 0
section = {}
reached = {k: False for k in roads}

for p in roads:
    if reached[p]:
        continue
    else:
        reached[p] = True
        stack = [p]
        section[p] = index
        while stack:
            v = stack.pop()
            i, j = p
            adj = []
            if i > 0 and S[i - 1, j] == '.':
                adj.append((i-1, j))
            if j > 0 and S[i, j - 1] == '.':
                adj.append((i, j - 1))
            if i < h-1 and S[i + 1, j] == '.':
                adj.append((i+1, j))
            if j < w-1 and S[i, j+1] == '.':
                adj.append((i, j+1))
            for u in adj:
                if not reached[u]:
                    reached[u] = True
                    stack.append(u)
                    section[u] = index
        index += 1

# print(roads)
# print(section)
if section[c] == section[d]:
    print(0)
    exit(0)

vertex = range(index)
edges = {i: set() for i in vertex}
for i, j in roads:
    head = section[i, j]
    square = product(range(max(i-2, 0), min(i+3, h)),
                     range(max(j-2, 0), min(j+3, w)))
    for m in square:
        if S[m] == '.':
            tail = section[m]
            if tail != head and S[m] == '.':
                edges[tail].add(head)
                edges[head].add(tail)

source = section[c]
target = section[d]
distance = {v: math.inf for v in vertex}
distance[source] = 0
reached_ = {k: False for k in vertex}
reached_[source] = True
queue = deque([source])
while queue:
    u = queue.popleft()
    for v in edges[u]:
        if not reached_[v]:
            reached_[v] = True
            distance[v] = distance[u] + 1
            queue.append(v)

if distance[target] != math.inf:
    print(distance[target])
else:
    print(-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
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):
            next_node = pick_next(node)
            if node:
                # mark node as traversed
                h, w = next_node
                visited[h][w] = True
                block.add(next_node)

                # go to next node
                DFS(next_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:
import sys
from collections import deque


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    h, w = nm()
    Ch, Cw = nm()
    Dh, Dw = nm()
    S = [list(ns()) for _ in range(h)]
    can_go = [(Ch, Cw)]
    pos = deque([(Ch, Cw)])
    visited = [[0] * w for _ in range(h)]
    visited[Ch - 1][Cw - 1] = 1

    while pos:
        c_i, c_j = pos.pop()
        for i, j in [(1, 0), (0, -1), (-1, 0), (0, 1)]:
            if 0 <= c_i + i - 1 < h and 0 <= c_j + j - 1 < w and not visited[c_i + i - 1][c_j + j - 1]:
                if S[c_i + i - 1][c_j + j - 1] == '.':
                    can_go.append((c_i + i, c_j + j))
                    pos.append((c_i + i, c_j + j))
                    visited[c_i + i - 1][c_j + j - 1] = 1

    cost = [[float('Inf')] * w for _ in range(h)]

    for i, j in can_go:
        cost[i - 1][j - 1] = 0

    warp = deque(can_go)

    while warp:
        c_i, c_j = warp.pop()
        for i in range(-2, 3):
            for j in range(-2, 3):
                if 0 <= c_i + i - 1 < h and 0 <= c_j + j - 1 < w \
                        and cost[c_i + i - 1][c_j + j - 1] > cost[c_i - 1][c_j - 1] + 1 \
                        and S[c_i + i - 1][c_j + j - 1] == '.':
                    cost[c_i + i - 1][c_j + j - 1] = cost[c_i - 1][c_j - 1] + 1
                    warp.append((c_i + i, c_j + j))

    print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != float('Inf') else -1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())
def nl(): return list(map(int, stdin.readline().split()))


def main():
    h, w = nm()
    Ch, Cw = nm()
    Dh, Dw = nm()
    S = [list(ns()) for _ in range(h)]
    can_go = [(Ch, Cw)]
    pos = deque([(Ch, Cw)])
    visited = [[0] * w for _ in range(h)]
    visited[Ch - 1][Cw - 1] = 1

    while pos:
        c_i, c_j = pos.pop()
        for i, j in [(1, 0), (0, -1), (-1, 0), (0, 1)]:
            if 0 <= c_i + i - 1 < h and 0 <= c_j + j - 1 < w and not visited[c_i + i - 1][c_j + j - 1]:
                if S[c_i + i - 1][c_j + j - 1] == '.':
                    can_go.append((c_i + i, c_j + j))
                    pos.append((c_i + i, c_j + j))
                    visited[c_i + i - 1][c_j + j - 1] = 1

    if (Dh, Dw) in can_go:
        print(0)
        return

    cost = [[float('Inf')] * w for _ in range(h)]

    for i, j in can_go:
        cost[i - 1][j - 1] = 0

    warp = deque(can_go)

    while warp:
        c_i, c_j = warp.pop()
        for i in range(-2, 3):
            for j in range(-2, 3):
                if 0 <= c_i + i - 1 < h and 0 <= c_j + j - 1 < w \
                        and cost[c_i + i - 1][c_j + j - 1] > cost[c_i - 1][c_j - 1] + 1 \
                        and S[c_i + i - 1][c_j + j - 1] == '.':
                    cost[c_i + i - 1][c_j + j - 1] = cost[c_i - 1][c_j - 1] + 1
                    warp.append((c_i + i, c_j + j))

    print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != float('Inf') else -1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
from math import ceil
import numpy as np


stdin = sys.stdin
def ns(): return stdin.readline().rstrip()
def ni(): return int(stdin.readline().rstrip())
def nm(): return map(int, stdin.readline().split())


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

# can_go_d = []
# dg = deque([(Dh, Dw)])

# while dg:
#     c_i, c_j = dg.pop()
#     for i in range(-2, 3):
#         for j in range(-2, 3):
#             if 0 <= c_i + i - 1 < h and 0 <= c_j + j - 1 < w:
#                 if not visited[c_i + i - 1][c_j + j - 1]:
#                     if S[c_i + i - 1][c_j + j - 1] == '.':
#                         can_go.append((c_i + i, c_j + j))
#                         pos.append((c_i + i, c_j + j))
#                         visited[c_i + i - 1][c_j + j - 1] = 1


def main():
    h, w = nm()
    Ch, Cw = nm()
    Dh, Dw = nm()
    S = np.array([list(ns()) for _ in range(h)])
    can_go = [(Ch, Cw)]
    pos = deque([(Ch, Cw)])
    visited = [[0] * w for _ in range(h)]
    visited[Ch - 1][Cw - 1] = 1

    while pos:
        c_i, c_j = pos.pop()
        for i, j in [(1, 0), (0, -1), (-1, 0), (0, 1)]:
            if 0 <= c_i + i - 1 < h and 0 <= c_j + j - 1 < w and not visited[c_i + i - 1][c_j + j - 1]:
                if S[c_i + i - 1][c_j + j - 1] == '.':
                    can_go.append((c_i + i, c_j + j))
                    pos.append((c_i + i, c_j + j))
                    visited[c_i + i - 1][c_j + j - 1] = 1

    if (Dh, Dw) in can_go:
        print(0)
        return

    cost = [[float('Inf')] * w for _ in range(h)]

    for i, j in can_go:
        cost[i - 1][j - 1] = 0

    warp = deque(can_go)

    while warp:
        c_i, c_j = warp.pop()
        for i in range(-2, 3):
            for j in range(-2, 3):
                if 0 <= c_i + i - 1 < h and 0 <= c_j + j - 1 < w \
                        and cost[c_i + i - 1][c_j + j - 1] > cost[c_i - 1][c_j - 1] + 1 \
                        and S[c_i + i - 1][c_j + j - 1] == '.':
                    cost[c_i + i - 1][c_j + j - 1] = cost[c_i - 1][c_j - 1] + 1
                    warp.append((c_i + i, c_j + j))

    print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != float('Inf') else -1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def Dijkstra(graph,s):
    INF = 10**9
    dist = [INF]*len(graph)
    dist[s] = 0
    #nn_node = [-1]*len(graph) #nearest neighborのnode
    #checked=[False]*len(graph) #dist 確定
    heap = [(0,s)]
    while heap:
        cost,node = hq.heappop(heap)
        if cost>dist[node]:continue
        for weight,nex in graph[node]:
            d = cost+weight
            if d<dist[nex]:
                dist[nex] = d
                #nn_node[nex] = node
                hq.heappush(heap,(d,nex))
    for i in range(len(dist)):
        if dist[i] == INF:
            dist[i] = -1
    return dist #,nn_node

dyx = [(-1,0),(1,0),(0,1),(0,-1)]
INF=10**9
H,W = ma()
ch,cw = ma()
ch-=1;cw-=1
dh,dw=ma()
dh-=1;dw-=1
area= []
for h in range(H):
    area.append(input())

group = [[-1]*W for h in range(H)]
def BFS(sy,sx,idx):
    que = collections.deque()
    que.append((sy,sx))
    group[sy][sx]=idx
    while que:
        h,w = que.popleft()
        for dy,dx in dyx:
            if (0<=h+dy<H )and (0<=w+dx<W):
                if area[h+dy][w+dx] =="." and group[h+dy][w+dx] ==-1:
                    group[h+dy][w+dx] = idx
                    que.append((h+dy,w+dx))


idx = 0
for h in range(H):
    for w in range(W):
        if area[h][w] =="." and group[h][w] ==-1:
            BFS(h,w,idx)
            idx+=1
            #print(group)

tree = [set() for _ in range(idx)]
dyx2 = [(-1,0),(1,0),(0,1),(0,-1),(-2,0),(2,0),(0,2),(0,-2)]
for h in range(H):
    for w in range(W):
        if area[h][w]=="#":
            continue
        g = group[h][w]
        for dy,dx in dyx2:
            if (0<=h+dy<H )and (0<=w+dx<W) and (area[h+dy][w+dx]=="."):
                if (g !=group[h+dy][w+dx]):
                    tree[g].add((1,group[h+dy][w+dx]))
                    tree[group[h+dy][w+dx]].add((1,g))
dist = Dijkstra(tree,group[ch][cw])

#print(group)
#print(tree)
#print(dist)
print(dist[group[dh][dw]])

Submission status: Wrong Answer

Solution code:
ma = lambda :map(int,input().split())
lma = lambda :list(map(int,input().split()))
tma = lambda :tuple(map(int,input().split()))
ni = lambda:int(input())
yn = lambda fl:print("Yes") if fl else print("No")
import collections
import math
import itertools
import heapq as hq
def Dijkstra(graph,s):
    INF = 10**9
    dist = [INF]*len(graph)
    dist[s] = 0
    #nn_node = [-1]*len(graph) #nearest neighborのnode
    #checked=[False]*len(graph) #dist 確定
    heap = [(0,s)]
    while heap:
        cost,node = hq.heappop(heap)
        if cost>dist[node]:continue
        for weight,nex in graph[node]:
            d = cost+weight
            if d<dist[nex]:
                dist[nex] = d
                #nn_node[nex] = node
                hq.heappush(heap,(d,nex))
    for i in range(len(dist)):
        if dist[i] == INF:
            dist[i] = -1
    return dist #,nn_node

dyx = [(-1,0),(1,0),(0,1),(0,-1)]
INF=10**9
H,W = ma()
ch,cw = ma()
ch-=1;cw-=1
dh,dw=ma()
dh-=1;dw-=1
area= []
for h in range(H):
    area.append(input())

group = [[-1]*W for h in range(H)]
def BFS(sy,sx,idx):
    que = collections.deque()
    que.append((sy,sx))
    group[sy][sx]=idx
    while que:
        h,w = que.popleft()
        for dy,dx in dyx:
            if (0<=h+dy<H )and (0<=w+dx<W):
                if area[h+dy][w+dx] =="." and group[h+dy][w+dx] ==-1:
                    group[h+dy][w+dx] = idx
                    que.append((h+dy,w+dx))


idx = 0
for h in range(H):
    for w in range(W):
        if area[h][w] =="." and group[h][w] ==-1:
            BFS(h,w,idx)
            idx+=1
            #print(group)

tree = [set() for _ in range(idx)]
dyx2 = [(-1,0),(1,0),(0,1),(0,-1),(-2,0),(2,0),(0,2),(0,-2)]
for h in range(H):
    for w in range(W):
        g = group[h][w]
        for dy,dx in dyx2:
            if (0<=h+dy<H )and (0<=w+dx<W) and (area[h+dy][w+dx]=="."):
                if (g !=group[h+dy][w+dx]):
                    tree[g].add((1,group[h+dy][w+dx]))
                    tree[group[h+dy][w+dx]].add((1,g))
dist = Dijkstra(tree,group[ch][cw])

#print(group)
#print(tree)
#print(dist)
print(dist[group[dh][dw]])