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: Time Limit Exceeded

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    H, W = LI()
    Ch, Cw = LI_()
    Dh, Dw = LI_()
    S = [SS() for _ in range(H)]

    d = ((1, 0), (0, 1), (-1, 0), (0, -1)) 
    d_warp = []
    for i in itertools.product(range(-2, 3), repeat=2):
        if i != (0, 0) and i not in d:
            d_warp.append(i)
    dist = [[INF] * W for _ in range(H)]
    que = collections.deque()
    que.append((Ch, Cw, 0))
    dist[Ch][Cw] = 0
    while que:
        cy, cx, cost = que.popleft()
        for dy, dx in d:
            ny = cy + dy
            nx = cx + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] == '.' and cost < dist[ny][nx] :
                dist[ny][nx] = cost
                que.appendleft((ny, nx, cost))
        for dy, dx in d_warp:
            ny = cy + dy
            nx = cx + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] == '.' and cost + 1 < dist[ny][nx] :
                dist[ny][nx] = cost + 1
                que.append((ny, nx, cost + 1))

    if dist[Dh][Dw] == INF:
        print(-1)
    else:
        print(dist[Dh][Dw])

if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

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 = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [(0, 0)] + move_a_area]

INF = 10**12
cost = [[INF] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m:
            continue
        cost[hh][ww] = m
        que.append((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m + 1:
            continue
        cost[hh][ww] = m + 1
        que.append((hh, ww, m + 1))

print(cost[d[0]][d[1]] if cost[d[0]][d[1]] < INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

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 = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [(0, 0)] + move_a_area]

cost = [[float('inf')] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m:
            continue
        cost[hh][ww] = m
        que.append((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m + 1:
            continue
        cost[hh][ww] = m + 1
        que.append((hh, ww, m + 1))

print(cost[d[0]][d[1]] if cost[d[0]][d[1]] < float('inf') else -1)

Submission status: Time Limit Exceeded

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    H, W = LI()
    Ch, Cw = LI_()
    Dh, Dw = LI_()
    S = [SS() for _ in range(H)]

    d = ((1, 0), (0, 1), (-1, 0), (0, -1)) 
    dist = [[INF] * W for _ in range(H)]
    que = collections.deque()
    que.append((Ch, Cw, 0))
    dist[Ch][Cw] = 0
    while que:
        cy, cx, cost = que.popleft()
        for dy, dx in d:
            ny = cy + dy
            nx = cx + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] == '.' and cost < dist[ny][nx] :
                dist[ny][nx] = cost
                que.appendleft((ny, nx, cost))
        for dy, dx in itertools.product(range(-2, 3), repeat=2):
            ny = cy + dy
            nx = cx + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] == '.' and cost + 1 < dist[ny][nx] :
                dist[ny][nx] = cost + 1
                que.append((ny, nx, cost + 1))

    if dist[Dh][Dw] == INF:
        print(-1)
    else:
        print(dist[Dh][Dw])

if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,input().split())
si,sj=map(int,input().split())
di,dj=map(int,input().split())

D =[]
for i in range(H):
  D.append([])
  tmp = input()
  for j in range(W):
  	D[i].append(tmp[j])


# デキューを用意する
from collections import deque
d = deque()

si-=1
sj-=1
di-=1
dj-=1
fx = [1,0,-1,0]
fy = [0,1,0,-1]
ans = [[-1 for j in range(W)] for i in range(H)]
ans[si][sj] = 0
Done = []

d.append((si,sj))
Done.append((si,sj))
while len(d) !=0:
    i,j = d.popleft()
    for x,y in zip(fx,fy):
        if i+x < 0 or i+x > H-1 or j+y <0 or j+y >W-1: continue
        if D[i+x][j+y] == "#":continue
        if ans[i+x][j+y] == 0 :continue
        if (i+x,j+y) in Done :continue
        d.appendleft((i+x,j+y))
        Done.append((i+x,j+y))
        ans[i+x][j+y] = ans[i][j]
    for mx in range(-2,3):
        for my in range(-2,3):
            if i+mx < 0 or i+mx > H-1 or j+my <0 or j+my >W-1: continue
            if D[i+mx][j+my] == "#":continue
            if ans[i+mx][j+my] != -1 :continue
            if ans[i+mx][j+my] == 0 :continue
            if (i+x,j+y) in Done :continue
            d.append((i+mx,j+my))
            ans[i+mx][j+my] = ans[i][j] + 1
print(ans[di][dj])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

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 = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [(0, 0)] + move_a_area]

cost = [[float('inf')] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m:
            continue
        cost[hh][ww] = m
        que.append((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m + 1:
            continue
        cost[hh][ww] = m + 1
        que.append((hh, ww, m + 1))

print(v if (v := cost[d[0]][d[1]]) < float('inf') else -1)

Submission status: Time Limit Exceeded

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    H, W = LI()
    Ch, Cw = LI_()
    Dh, Dw = LI_()
    S = [SS() for _ in range(H)]

    d = ((1, 0), (0, 1), (-1, 0), (0, -1)) 
    dist = [[INF] * W for _ in range(H)]
    que = collections.deque()
    que.append((Ch, Cw, 0))
    dist[Ch][Cw] = 0
    while que:
        cy, cx, cost = que.popleft()
        for dy, dx in d:
            ny = cy + dy
            nx = cx + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] == '.' and cost < dist[ny][nx] :
                dist[ny][nx] = cost
                que.appendleft((ny, nx, cost))
        for dy, dx in itertools.product(range(-2, 3), repeat=2):
            ny = cy + dy
            nx = cx + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] == '.' and cost < dist[ny][nx] :
                dist[ny][nx] = cost + 1
                que.append((ny, nx, cost + 1))

    if dist[Dh][Dw] == INF:
        print(-1)
    else:
        print(dist[Dh][Dw])

if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,input().split())
si,sj=map(int,input().split())
di,dj=map(int,input().split())

D =[]
for i in range(H):
  D.append([])
  tmp = input()
  for j in range(W):
  	D[i].append(tmp[j])


# デキューを用意する
from collections import deque
d = deque()

si-=1
sj-=1
di-=1
dj-=1
fx = [1,0,-1,0]
fy = [0,1,0,-1]
ans = [[-1 for j in range(W)] for i in range(H)]
ans[si][sj] = 0
Done = []

d.append((si,sj))
Done.append((si,sj))
while len(d) !=0:
    i,j = d.popleft()
    for x,y in zip(fx,fy):
        if i+x < 0 or i+x > H-1 or j+y <0 or j+y >W-1: continue
        if D[i+x][j+y] == "#":continue
        if ans[i+x][j+y] == 0 :continue
        if (i+x,j+y) in Done :continue
        d.appendleft((i+x,j+y))
        Done.append((i+x,j+y))
        ans[i+x][j+y] = ans[i][j]
    for mx in range(-2,3):
        for my in range(-2,3):
            if i+mx < 0 or i+mx > H-1 or j+my <0 or j+my >W-1: continue
            if D[i+mx][j+my] == "#":continue
            if ans[i+mx][j+my] != -1 :continue
            if ans[i+mx][j+my] == 0 :continue
            d.append((i+mx,j+my))
            ans[i+mx][j+my] = ans[i][j] + 1
print(ans[di][dj])

Submission status: Time Limit Exceeded

Solution code:
# import numpy as np
from collections import deque

H,W=map(int,input().split())
CH,CW=map(int,input().split())
DH,DW=map(int,input().split())

S=[list(input()) for _ in range(H)]
MAX_COST = 10 ** 9
Cost=[ [ MAX_COST for _ in range(W)] for _ in range(H)]
# Cost = np.full((H,W),MAX_COST)

# print(S)

ans = -1

deq = deque()

deq.append((CH-1,CW-1,0))
Cost[CH-1][CW-1] = 0;

# used = set()
five_five = [ (i,j) for i in range(-2,3,1) for j in range(-2,3,1) ]
ffCosts = {}
for i,j in five_five:
	# print(i,j)
	if (j == 0 and (i==1 or i==-1)) or (i==0 and (j==1 or j==-1)):
		ffCosts[(i,j)] = 0
	else:
		ffCosts[(i,j)] = 1
# print(five_five)

while 0 < len(deq):
	h,w,c=deq.popleft()
	# print(h,w,c)
	for i,j in five_five:
		# print(i,j)
		if 0 <= h+i and h+i < H and 0 <= w+j and w+j < W:
			if S[h+i][w+j] == '.':
				cAdd = ffCosts[(i,j)]
				if c + cAdd < Cost[h+i][w+j]:
					Cost[h+i][w+j] = c + cAdd
					if cAdd == 0:
						deq.appendleft((h+i,w+j,Cost[h+i][w+j]))
					else:
						deq.append((h+i,w+j,Cost[h+i][w+j]))

if Cost[DH-1][DW-1] == MAX_COST:
	print(-1)
else:
	print(Cost[DH-1][DW-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

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 = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [0, 0] + move_a_area]

INF = 10**12
cost = [[INF] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if 0 <= hh < h and 0 <= ww < w and s[hh][ww] == '.' and cost[hh][ww] > m:
            cost[hh][ww] = m
            que.append((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if 0 <= hh < h and 0 <= ww < w and s[hh][ww] == '.' and cost[hh][ww] > m + 1:
            cost[hh][ww] = m + 1
            que.append((hh, ww, m + 1))

print(v if (v := cost[d[0]][d[1]]) < INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

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 = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [0, 0] + move_a_area]

INF = 10**12
cost = [[INF] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m:
            continue
        cost[hh][ww] = m
        que.append((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m + 1:
            continue
        cost[hh][ww] = m + 1
        que.append((hh, ww, m + 1))

print(v if (v := cost[d[0]][d[1]]) < INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

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 = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [0, 0] + move_a_area]

cost = [[float('inf')] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m:
            continue
        cost[hh][ww] = m
        que.append((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m + 1:
            continue
        cost[hh][ww] = m + 1
        que.append((hh, ww, m + 1))

print(cost[d[0]][d[1]] if cost[d[0]][d[1]] < float('inf') else -1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

H,W=map(int,input().split())
CH,CW=map(int,input().split())
DH,DW=map(int,input().split())

S=[list(input()) for _ in range(H)]
MAX_COST = 10 ** 9
# Cost=[ [ MAX_COST for _ in range(W)] for _ in range(H)]
Cost = np.full((H,W),MAX_COST)

# print(S)

ans = -1

deq = deque()

deq.append((CH-1,CW-1,0))
Cost[CH-1][CW-1] = 0;

# used = set()
five_five = [ (i,j) for i in range(-2,3,1) for j in range(-2,3,1) ]
# print(five_five)

while 0 < len(deq):
	h,w,c=deq.popleft()
	# print(h,w,c)
	for i,j in five_five:
		# print(i,j)
		if 0 <= h+i and h+i < H and 0 <= w+j and w+j < W:
			if S[h+i][w+j] == '.':
				if (j == 0 and (i==1 or i==-1)) or (i==0 and (j==1 or j==-1)):
					if c < Cost[h+i][w+j]:
						Cost[h+i][w+j] = c
						deq.appendleft((h+i,w+j,Cost[h+i][w+j]))
				elif c + 1 < Cost[h+i][w+j]:
					Cost[h+i][w+j] = c + 1
					deq.append((h+i,w+j,Cost[h+i][w+j]))
					# print("updr ", h+i,w+j,Cost[h+i][w+j])

if Cost[DH-1][DW-1] == MAX_COST:
	print(-1)
else:
	print(Cost[DH-1][DW-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

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 = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [0, 0] + move_a_area]

cost = [[float('inf')] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m:
            continue
        cost[hh][ww] = m
        que.append((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m + 1:
            continue
        cost[hh][ww] = m + 1
        que.append((hh, ww, m + 1))

print(v if (v := cost[d[0]][d[1]]) < float('inf') else -1)

Submission status: Time Limit Exceeded

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(input()) for _ in range(H)]
MAX_COST = 10 ** 9
Cost=[ [ MAX_COST for _ in range(W)] for _ in range(H)]

# print(S)

ans = -1

deq = deque()

deq.append((CH-1,CW-1,0))
Cost[CH-1][CW-1] = 0;

# used = set()
five_five = [ (i,j) for i in range(-2,3,1) for j in range(-2,3,1) ]
# print(five_five)

while 0 < len(deq):
	h,w,c=deq.popleft()
	# print(h,w,c)
	for i,j in five_five:
		# print(i,j)
		if 0 <= h+i and h+i < H and 0 <= w+j and w+j < W:
			if S[h+i][w+j] == '.':
				if (j == 0 and (i==1 or i==-1)) or (i==0 and (j==1 or j==-1)):
					if c < Cost[h+i][w+j]:
						Cost[h+i][w+j] = c
						deq.appendleft((h+i,w+j,Cost[h+i][w+j]))
				elif c + 1 < Cost[h+i][w+j]:
					Cost[h+i][w+j] = c + 1
					deq.append((h+i,w+j,Cost[h+i][w+j]))
					# print("updr ", h+i,w+j,Cost[h+i][w+j])

if Cost[DH-1][DW-1] == MAX_COST:
	print(-1)
else:
	print(Cost[DH-1][DW-1])

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int,input().split())
start = tuple(map(int, input().split()))
goal = tuple(map(int, input().split()))
visited = {(i, j): False for i in range(1, h + 1) for j in range(1, w + 1)}
maze = {}
for i in range(h):
    row = input()
    for j in range(len(row)):
        maze[(i+1, j+1)] = row[j]

def check_bound(coordinate):
    if (1 <= coordinate[0] & coordinate[0] <= h) & (1<= coordinate[1] & coordinate[1] <= w):
        return True
    else:
        return False


def add(cor1, cor2):
    return (cor1[0] + cor2[0], cor1[1] + cor2[1])


def walk(start):
    visited[start] = True
    for dir in [(1,0), (-1, 0), (0, 1), (0, -1)]:
        cor = add(start, dir)
        if check_bound(cor):
            if (not visited[cor]) & (maze[cor] == '.'):
                walk(cor)


def warp(start):
    flag = False
    for jump in [(i, j) for i in range(-2, 3) for j in range(-2, 3)]:
        cor = add(start, jump)
        if check_bound(cor):
            if (not visited[cor]) & (maze[cor] == '.'):
                walk(cor)
                flag = True
    return flag

walk(start)
warp_count = 0
while not visited[goal]:
    prev_visited = visited.copy()
    flag = False
    for cor in prev_visited.keys():
        if prev_visited[cor]:
            flag = flag or warp(cor)
    if not flag:
        break
    warp_count += 1
    

if visited[goal]:
    print(warp_count)
else:
    print(-1)

Submission status: Time Limit Exceeded

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(input()) for _ in range(H)]
MAX_COST = 10 ** 9
Cost=[ [ MAX_COST for _ in range(W)] for _ in range(H)]

# print(S)

ans = -1

deq = deque()

deq.append((CH-1,CW-1,0))
Cost[CH-1][CW-1] = 0;

# used = set()
five_five = [ (i,j) for i in range(-2,3,1) for j in range(-2,3,1) ]
# print(five_five)

while 0 < len(deq):
	h,w,c=deq.popleft()
	# print(h,w,c)
	for i,j in five_five:
		# print(i,j)
		if 0 <= h+i and h+i < H and 0 <= w+j and w+j < W:
			if S[h+i][w+j] == '.':
				if (j == 0 and abs(i)==1) or (i==0 and abs(j)==1):
					if c < Cost[h+i][w+j]:
						Cost[h+i][w+j] = c
						deq.appendleft((h+i,w+j,Cost[h+i][w+j]))
				elif c + 1 < Cost[h+i][w+j]:
					Cost[h+i][w+j] = c + 1
					deq.append((h+i,w+j,Cost[h+i][w+j]))
					# print("updr ", h+i,w+j,Cost[h+i][w+j])

if Cost[DH-1][DW-1] == MAX_COST:
	print(-1)
else:
	print(Cost[DH-1][DW-1])

Submission status: Time Limit Exceeded

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(input()) for _ in range(H)]
MAX_COST = 10 ** 9
Cost=[ [ MAX_COST for _ in range(W)] for _ in range(H)]

# print(S)

ans = -1

deq = deque()

deq.append((CH-1,CW-1,0))
Cost[CH-1][CW-1] = 0;

# used = set()

while 0 < len(deq):
	h,w,c=deq.popleft()
	# print(h,w,c)
	for i in range(-2,3,1):
		for j in range(-2,3,1):
			# print(i,j)
			if 0 <= h+i and h+i < H and 0 <= w+j and w+j < W:
				if S[h+i][w+j] == '.':
					if (j == 0 and abs(i)==1) or (i==0 and abs(j)==1):
						if c < Cost[h+i][w+j]:
							Cost[h+i][w+j] = c
							deq.appendleft((h+i,w+j,Cost[h+i][w+j]))
					elif c + 1 < Cost[h+i][w+j]:
						Cost[h+i][w+j] = c + 1
						deq.append((h+i,w+j,Cost[h+i][w+j]))
						# print("updr ", h+i,w+j,Cost[h+i][w+j])

if Cost[DH-1][DW-1] == MAX_COST:
	print(-1)
else:
	print(Cost[DH-1][DW-1])

Submission status: Time Limit Exceeded

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 = [input() for i in range(H)]
INF = 10 ** 9
walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]
h = CH
w = CW
Distance = [[INF] * W for _ in range(H)]
Distance[h][w] = 0
q = deque(())
q.append((h,w))
while q:
  h,w = q.popleft()
  if [h,w] == [DH,DW]:
    break
  for i,j in walk:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h][w] < Distance[hwalk][wwalk]:
      Distance[hwalk][wwalk] = Distance[h][w]
      q.appendleft((hwalk,wwalk))
  for i,j in warp:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h][w] + 1 < Distance[hwalk][wwalk]:
      Distance[hwalk][wwalk] = Distance[h][w] + 1
      q.append((hwalk,wwalk))
print(int(Distance[DH][DW]) if Distance[DH][DW] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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 = [input() for i in range(H)]
INF = 10 ** 9
walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]
h = CH
w = CW
Distance = [[INF] * W for _ in range(H)]
Distance[h][w] = 0
q = deque(())
q.append((h,w))
while q:
  h,w = q.popleft()
  if [h,w] == [DH,DW]:
    break
  for i,j in walk:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h][w] < Distance[hwalk][wwalk]:
      Distance[hwalk][wwalk] = Distance[h][w]
      q.appendleft((hwalk,wwalk))
  for i,j in warp:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h][w] + 1 < Distance[hwalk][wwalk]:
      Distance[hwalk][wwalk] = Distance[h][w] + 1
      q.append((hwalk,wwalk))
print(int(Distance[DH][DW]) if Distance[DH][DW] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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 = [input() for i in range(H)]
INF = 10 ** 9
walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]
h = CH
w = CW
Distance = [[INF] * W for _ in range(H)]
Distance[h][w] = 0
q = deque([])
q.append([h,w])
while q:
  h,w = q.popleft()
  if [h,w] == [DH,DW]:
    break
  for i,j in walk:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h][w] < Distance[hwalk][wwalk]:
      Distance[hwalk][wwalk] = Distance[h][w]
      q.appendleft([hwalk,wwalk])
  for i,j in warp:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h][w] + 1 < Distance[hwalk][wwalk]:
      Distance[hwalk][wwalk] = Distance[h][w] + 1
      q.append([hwalk,wwalk])
print(int(Distance[DH][DW]) if Distance[DH][DW] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
def solve(h,w,ch,cw,dh,hw,s):
    d=[[1,0],[-1,0],[0,1],[0,-1]]
    warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + d]
    INF=10**12
    path=[[INF]*w for _ in range(h)]
    ans=0
    st=[]
    st=deque()
    st.append((ch,cw,0))
    wp=[]
    wp=deque()
    while st:
      nx,ny,ncost=st.popleft()
      wp.append((nx,ny,ncost))
      path[nx][ny]=ncost
      for dx,dy in d:
        x=nx+dx
        y=ny+dy
        if (0<=x<=h-1) and (0<=y<=w-1):
          if s[x][y]!='#' and path[x][y]>ncost:
            path[x][y]=ncost
            st.append((x,y,ncost))
      if len(st)==0:
        while wp:
          nx,ny,ncost=wp.popleft()
          for dx,dy in warp:
              x,y=nx+dx,ny+dy
              if (0<=x<=h-1) and (0<=y<=w-1):
                if s[x][y]!='#' and path[x][y]>ncost+1:
                  path[x][y]=ncost+1
                  st.append((x,y,ncost+1))
    if path[dh][dw]==INF:
      print(-1)
    else:
      print(path[dh][dw])

if __name__ == '__main__':
    import sys
    input = sys.stdin.readline
    from collections import deque
    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
    s=[input() for _ in range(h)]
    solve(h,w,ch,cw,dh,dw,s)

Submission status: Time Limit Exceeded

Solution code:
def solve(h,w,ch,cw,dh,hw,s):
    d=[[1,0],[-1,0],[0,1],[0,-1]]
    INF=10**12
    path=[[INF]*w for _ in range(h)]
    ans=0
    st=[]
    st=deque()
    st.append((ch,cw,0))
    wp=[]
    wp=deque()
    while st:
      nx,ny,ncost=st.popleft()
      wp.append((nx,ny,ncost))
      path[nx][ny]=ncost
      for dx,dy in d:
        x=nx+dx
        y=ny+dy
        if (0<=x<=h-1) and (0<=y<=w-1):
          if s[x][y]!='#' and path[x][y]>ncost:
            path[x][y]=ncost
            st.append((x,y,ncost))
      if len(st)==0:
        while wp:
          nx,ny,ncost=wp.popleft()
          for i in range(-2,3):
            for j in range(-2,3):
              if (i,j)==(0,0) or (i,j)==(1,0) or (i,j)==(0,1) or (i,j)==(-1,0) or (i,j)==(0,-1):
                continue
              x,y=i+nx,j+ny
              if (0<=x<=h-1) and (0<=y<=w-1):
                if s[x][y]!='#' and path[x][y]>ncost+1:
                  path[x][y]=ncost+1
                  st.append((x,y,ncost+1))
    if path[dh][dw]==INF:
      print(-1)
    else:
      print(path[dh][dw])

if __name__ == '__main__':
    import sys
    input = sys.stdin.readline
    from collections import deque
    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
    s=[input() for _ in range(h)]
    solve(h,w,ch,cw,dh,dw,s)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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 = [input() for i in range(H)]
INF = 10 ** 9
walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]
h = CH
w = CW
Distance = np.ones((H,W)) * INF
Distance[h,w] = 0
q = deque([])
q.append([h,w])
while q:
  h,w = q.popleft()
  if [h,w] == [DH,DW]:
    break
  for i,j in walk:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h,w] < Distance[hwalk,wwalk]:
      Distance[hwalk,wwalk] = Distance[h,w]
      q.appendleft([hwalk,wwalk])
  for i,j in warp:
    hwalk = h + i
    wwalk = w + j
    if 0 <= hwalk < H and 0 <= wwalk < W and S[hwalk][wwalk] == '.' and Distance[h,w] + 1 < Distance[hwalk,wwalk]:
      Distance[hwalk,wwalk] = Distance[h,w] + 1
      q.append([hwalk,wwalk])
print(int(Distance[DH,DW]) if Distance[DH,DW] != INF else -1)