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

h,w = map(int,input().split())#行,列
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = [list(input()) for _ in range(h)]

cost = {i:{j:-1 for j in range(w)} for i in range(h)}
cost[C[0]-1][C[1]-1]=0
cost_base = 0

ok = True

q=deque()
while cost[D[0]-1][D[1]-1]==-1:
    #スタート(初回)と、前回ループで移動Bで初めて行けたマスの登録
    for i in range(h):
        for j in range(w):
            if cost[i][j]==cost_base:
                q.append([i+1,j+1])
                
    #どちらの移動でも、ゴール踏破前に未踏破のマスに行けなかった場合
    if len(q)==0:
        ok = False
        break
                
    #移動Aで行けるマスを全探索
    while len(q)>0:
        now = q.popleft()
        dh = [-1,1]
        dw = [-1,1]
        for i in dh:
            if now[0]+i<1 or now[0]+i>h:
                continue
            if S[now[0]+i-1][now[1]-1]=='.' and cost[now[0]+i-1][now[1]-1]==-1:
                cost[now[0]+i-1][now[1]-1]=cost_base
                q.append([now[0]+i,now[1]])
        for j in dw:
            if now[1]+j<1 or now[1]+j>w:
                continue
            if S[now[0]-1][now[1]+j-1]=='.' and cost[now[0]-1][now[1]+j-1]==-1:
                cost[now[0]-1][now[1]+j-1]=cost_base
                q.append([now[0],now[1]+j])

    #移動Aで行けたマスから移動Bで行け、かつ今まで行けなかったマスの探索
    for _h in range(h):
        for _w in range(w):
            if cost[_h][_w]==cost_base:
                
                dr = [-2,-1,0,1,2]
                for i in dr:
                    for j in dr:
                        if _h+1+i<1 or _h+1+i>h:
                            continue
                        if _w+1+j<1 or _w+1+j>w:
                            continue

                        if S[_h+i][_w+j]=='.' and cost[_h+i][_w+j]==-1:
                            cost[_h+i][_w+j]=cost_base+1
    cost_base+=1
    
if ok:
    print(cost[D[0]-1][D[1]-1])
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
sx, sy = map(int, input().split())
sx -= 1; sy -= 1
tx, ty = map(int, input().split())
tx -= 1; ty -= 1

S = [input() for _ in range(H)]


dxy = [(-1, 0), (0, -1), (1, 0), (0, 1)]
dist = {(sx, sy) : 0}
next_points = set([(sx, sy)])
def bfs(d):
    global dist, next_points
    stack = list(next_points)
    next_points = set()
    while stack:
        x, y = stack.pop()
        dist[(x, y)] = d
        count = 0
        for dx, dy in dxy:
            xx = x + dx; yy = y + dy
            if 0 <= xx < H and 0 <= yy < W and S[xx][yy] == '.':
                count += 1
                if (xx, yy) not in dist:
                    dist[(xx, yy)] = d
                    stack.append((xx, yy))
        
        if count < 4:
            for dx in range(-2, 3):
                xx = x + dx
                for dy in range(-2, 3):
                    yy = y + dy
                    if (xx, yy) not in dist and 0 <= xx < H and 0 <= yy < W and S[xx][yy] == '.':
                        next_points.add((xx, yy))

d = 0
while (tx, ty) not in dist:
    bfs(d)
    d += 1
    if len(next_points) == 0:
        if (tx, ty) in dist:
            print(dist[(tx, ty)])
        else:
            print(-1)
        quit()

print(dist[(tx, ty)])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
import numpy as np
import numba
from numba import njit, b1, i4, i8, f8



h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())
mp = [None]+[[None]+[c for c in input()] for _ in range(h)]

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

cost = 0

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

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

from numba import jit

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

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


main()

Submission status: Time Limit Exceeded

Solution code:
import sys, math, heapq



if(__name__ == "__main__"):
    """
    N = int( input().strip() )
    Length = list( map(int, input().strip().split() ) )
    """
    H, W= map(int, input().strip().split() )
    start = list( map(int, input().strip().split() ) )
    goal = list( map(int, input().strip().split() ) )
    for i in range(2):
        start[i] -= 1
        goal[i] -= 1
    Maps = [ [] for _ in range(H) ]
    for i in range(H):
        Maps[i] = input().strip()

    inf = 10**7

    deque = []
    dists = [ [inf for _ in range(W) ] for _ in range(H)]

    heapq.heappush(deque, [0, start[1], start[0]])
    dists[start[0]][start[1]] = 0
    while( len(deque)>0 ):
        dist_pos = heapq.heappop(deque)

        x, y = [dist_pos[1], dist_pos[2] ]
        if(dists[y][x] < dist_pos[0]):
            continue
        Flag = -1 # L, R, D, U
        N_Flag = 0
        for dx, dy, i in ( (-1, 0, 0), (1, 0, 1), (0, -1, 2), (0, 1, 3) ):
            if( x+ dx < 0 or x+ dx > W-1 or y+ dy < 0 or y+ dy > H-1):
                continue
            if(Maps[y+dy][x+dx]=="#"):
                Flag = i
                N_Flag += 1
                continue

            next = [x+ dx, y+ dy]
            #print([x, y], next)
            if(dists[next[1] ][next[0] ] > dists[y][x]):
                dists[next[1] ][next[0] ] = dists[y][x]
                heapq.heappush(deque, [dists[next[1] ][next[0] ], next[0], next[1] ])

        if(N_Flag>1):
            dy_max = min(H-y, 3)
            dy_min = max(-y, -2)
            dx_min = max(-x, -2)
            dx_max = min(W-x, 3)
            for dy in range( dy_min, dy_max ):
                for dx in range( dx_min, dx_max ):
                    next = [x+ dx, y+ dy]
                    if(Maps[y+dy][x+dx] == "." and dists[next[1] ][next[0] ] == inf):
                        dists[next[1] ][next[0] ] = dists[y][x]+1
                        heapq.heappush(deque, [dists[next[1] ][next[0] ], next[0], next[1] ])

        elif(N_Flag > 0):
            # L, R, D, U
            dy_max = min(H-y, 3)
            dy_min = max(-y, -2)
            dx_min = max(-x, -2)
            dx_max = min(W-x, 3)
            if(Flag == 3):
                dy_min = 1
            elif(Flag == 2):
                dy_max = 0
            elif(Flag == 1):
                dx_min = 1
            else:
                dx_max = 0
            for dy in range( dy_min, dy_max ):
                for dx in range( dx_min, dx_max ):
                    next = [x+ dx, y+ dy]
                    if(Maps[y+dy][x+dx] == "." and dists[next[1] ][next[0] ] == inf):
                        dists[next[1] ][next[0] ] = dists[y][x]+1
                        heapq.heappush(deque, [dists[next[1] ][next[0] ], next[0], next[1] ])




    #print(dists)
    if( dists[goal[0]][goal[1]]==inf ):
        print(-1)
    else:
        print(dists[goal[0]][goal[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())
Ch -= 1
Cw -= 1
Dh -= 1
Dw -= 1
t = [[i for i in range(w)] for j in range(h)]
ans = 0
for i in range(h):
  temp = input()
  for j in range(w):
    t[i][j] = temp[j]

d = deque()
d.append((Ch, Cw))
ans = 0
s = set() # いったところ
a = [(1,0),(-1,0),(0,1),(0,-1),(0,0)]
b = [-2,-1,0,1,2]
while True:
  flag = True
  # 行けるところすべて追加
  while flag:
    flag = False
    for _ in range(len(d)):
      Th, Tw = d.popleft()
      for i,j in a:
        _h = Th + i
        _w = Tw + j
        _p = (_h, _w)
        if (not (_p) in d) and _h >= 0 and _h < h and _w >= 0 and _w < w and t[_h][_w] == '.':
          d.append(_p)
          if not(i == 0 and j == 0):
            flag = True
  # クリアしてるか確認
  temps = set(d)
  if (Dh,Dw) in temps:
    print(ans)
    exit()
  else:
    s |= temps
    d = deque()
    for Th,Tw in temps:
      for i in b:
        for j in b:
          _h = Th + i
          _w = Tw + j
          _p = (_h, _w)
          if (not (_p) in s) and (not (_p) in d) and _h >= 0 and _h < h and _w >= 0 and _w < w and t[_h][_w] == '.':
            d.append(_p)
    if len(d) == 0:
      print('-1')
      exit()
    ans += 1

Submission status: Time Limit Exceeded

Solution code:
import queue
q = queue.Queue()

INF = 10**9
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)]
t = [[INF for _ in range(w)] for _ in range(h)]
q.put((ch, cw))
t[ch][cw] = 0


def test(x, y, new_v):
    if 0 <= x < h and 0 <= y < w and s[x][y] == ".":
        old_v = t[x][y]
        if new_v < old_v:
            t[x][y] = new_v
            q.put((x, y))


while not q.empty():
    x, y = q.get()
    v = t[x][y]
    test(x - 1, y, v)
    test(x + 1, y, v)
    test(x, y - 1, v)
    test(x, y + 1, v)

    for i in range(3):
        for j in range(3):
            test(x - i, y - j, v + 1)
            test(x - i, y + j, v + 1)
            test(x + i, y - j, v + 1)
            test(x + i, y + j, v + 1)

ans = t[dh][dw]
print(-1 if ans == INF else ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
q = queue.Queue()

INF = 10**9
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)]
t = [[INF for _ in range(w)] for _ in range(h)]
q.put((ch, cw))
t[ch][cw] = 0


def test(x, y, new_v):
    if 0 <= x < h and 0 <= y < w and s[x][y] == ".":
        old_v = t[x][y]
        if new_v < old_v:
            t[x][y] = new_v
            q.put((x, y))


while not q.empty():
    x, y = q.get()
    v = t[x][y]
    test(x - 1, y, v)
    test(x + 1, y, v)
    test(x, y - 1, v)
    test(x, y + 1, v)

    for i in range(3):
        for j in range(3):
            test(x - i, y - j, v + 1)
            test(x - i, y + j, v + 1)
            test(x + i, y - j, v + 1)
            test(x + i, y + j, v + 1)

ans = t[dh][dw]
print(-1 if ans == INF else ans)

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())
mp = [None]+[[None]+[c for c in input()] for _ in range(h)]

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

cost = 0

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

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


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

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

# print(mp)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w = map(int,input().split())#行,列
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = [list(input()) for _ in range(h)]

cost = [[-1]*w for _ in range(h)]
cost[C[0]-1][C[1]-1]=0
cost_base = 0

ok = True

q=deque()
while cost[D[0]-1][D[1]-1]==-1:
    #スタート(初回)と、前回ループで移動Bで初めて行けたマスの登録
    for i in range(h):
        for j in range(w):
            if cost[i][j]==cost_base:
                q.append([i+1,j+1])
                
    #どちらの移動でも、ゴール踏破前に未踏破のマスに行けなかった場合
    if len(q)==0:
        ok = False
        break
                
    #移動Aで行けるマスを全探索
    while len(q)>0:
        now = q.popleft()
        dh = [-1,1]
        dw = [-1,1]
        for i in dh:
            if now[0]+i<1 or now[0]+i>h:
                continue
            if S[now[0]+i-1][now[1]-1]=='.' and cost[now[0]+i-1][now[1]-1]==-1:
                cost[now[0]+i-1][now[1]-1]=cost_base
                q.append([now[0]+i,now[1]])
        for j in dw:
            if now[1]+j<1 or now[1]+j>w:
                continue
            if S[now[0]-1][now[1]+j-1]=='.' and cost[now[0]-1][now[1]+j-1]==-1:
                cost[now[0]-1][now[1]+j-1]=cost_base
                q.append([now[0],now[1]+j])

    #移動Aで行けたマスから移動Bで行け、かつ今まで行けなかったマスの探索
    for _h in range(h):
        for _w in range(w):
            if cost[_h][_w]==cost_base:
                dr = [-2,-1,0,1,2]

                for i in dr:
                    for j in dr:
                        if _h+1+i<1 or _h+1+i>h:
                            continue
                        if _w+1+j<1 or _w+1+j>w:
                            continue

                        if S[_h+i][_w+j]=='.' and cost[_h+i][_w+j]==-1:
                            cost[_h+i][_w+j]=cost_base+1
    cost_base+=1

if ok:
    print(cost[D[0]-1][D[1]-1])
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
import sys

f_inf = float("inf")

# Input#
# n = int(input())
h, w = map(int, input().split())
c_h, c_w = map(int, input().split())
d_h, d_w = map(int, input().split())

grid = []

d = deque()


for i in range(h + 1):
    if i == 0:
        array_tmp = "#" * w
    else:
        array_tmp = str(input().strip())
    array_tmp = "#" + array_tmp
    grid.append(list(array_tmp))


grid[c_h][c_w] = 0

d.append((c_h, c_w))


def check(tar_h, tar_w):
    if tar_h > h or tar_h < 1:
        return -1
    if tar_w > w or tar_w < 1:
        return -1
    if grid[tar_h][tar_w] == ".":
        return f_inf
    if grid[tar_h][tar_w] == "#":
        return -1
    else:
        return grid[tar_h][tar_w]


while len(d) != 0:
    tar_h, tar_w = d.popleft()
    tar_num = grid[tar_h][tar_w]
    if tar_num == "#":
        continue

    for i in range(5):
        for j in range(5):
            if check(tar_h + i - 2, tar_w + j - 2) > tar_num:
                if (
                    (i == 2 and j == 1)
                    or (i == 2 and j == 3)
                    or (i == 1 and j == 2)
                    or (i == 3 and j == 2)
                ):
                    grid[tar_h + i - 2][tar_w + j - 2] = tar_num
                    d.appendleft((tar_h + i - 2, tar_w + j - 2))
                    if tar_h == d_h and tar_w == d_w:
                        print("{}".format(tar_num))
                        sys.exit()
                else:
                    grid[tar_h + i - 2][tar_w + j - 2] = tar_num + 1
                    d.append((tar_h + i - 2, tar_w + j - 2))

if check(d_h, d_w) == f_inf:
    ans = -1
else:
    ans = check(d_h, d_w)

print("{}".format(ans))

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())
Ch -= 1
Cw -= 1
Dh -= 1
Dw -= 1
t = [[i for i in range(w)] for j in range(h)]
ans = 0
for i in range(h):
  temp = input()
  for j in range(w):
    t[i][j] = temp[j]

d = deque()
d.append((Ch, Cw))
ans = 0
s = set() # いったところ

while True:
  flag = True
  # 行けるところすべて追加
  while flag:
    flag = False
    for _ in range(len(d)):
      Th, Tw = d.popleft()
      for i,j in [(1,0),(-1,0),(0,1),(0,-1),(0,0)]:
        _h = Th + i
        _w = Tw + j
        _p = (_h, _w)
        if (not (_p) in d) and _h >= 0 and _h < h and _w >= 0 and _w < w and t[_h][_w] == '.':
          d.append(_p)
          if not(i == 0 and j == 0):
            flag = True
  # クリアしてるか確認
  temps = set(d)
  if (Dh,Dw) in temps:
    print(ans)
    exit()
  else:
    s |= temps
    d = deque()
    for Th,Tw in temps:
      for i in [-2,-1,0,1,2]:
        for j in [-2,-1,0,1,2]:
          _h = Th + i
          _w = Tw + j
          _p = (_h, _w)
          if (not (_p) in s) and (not (_p) in d) and _h >= 0 and _h < h and _w >= 0 and _w < w and t[_h][_w] == '.':
            d.append(_p)
    if len(d) == 0:
      print('-1')
      exit()
    ans += 1

Submission status: Time Limit Exceeded

Solution code:
class P:
    def __init__(self, c):
        self.c = c
        self.reached = False
        self.searched = False
        self.checked = False

from collections import deque
H, W = [int(i) for i in input().split()]
Ch, Cw = [int(i)-1 for i in input().split()]
Dh, Dw = [int(i)-1 for i in input().split()]
S = [[None for _ in range(H)] for _ in range(W)]
for y in range(H):
    tmp = input()
    for x in range(W):
        S[x][y] = P(tmp[x])

def neighbors(x, y, d):
    for i in range(max(0, x-1), min(W, x+2)):
        if S[i][y].reached == False and S[i][y].c == '.':
            d.append((i, y))
    for i in range(max(0, y-1), min(H, y+2)):
        if S[x][i].reached == False and S[x][i].c == '.':
            d.append((x, i))

def jump(x, y, d):
    S[x][y].checked = True
    for i in range(max(0, x-2), min(W, x+3)):
        for j in range(max(0, y-2), min(H, y+3)):
            if  S[i][j].c == '.' and S[i][j].searched == False and S[i][j].reached == False:
                d.append((i, j))
            S[i][j].searched = True


def BFS(x, y):
    d = deque([(x, y)])
    route = deque([])
    while True:
        x, y = d.popleft()
        route.append((x, y))
        S[x][y].reached = True
        neighbors(x, y, d)
        if len(d) == 0:
            break
    return route


counter = 0
if Cw == Dw and Ch == Dh:
    print(0)
    exit()
q = deque([(Cw, Ch)])
flag = False
while True:
    array = []
    while len(q) > 0:
        x, y = q.popleft()
        if S[x][y].reached:
            pass
        else:
            array.append(BFS(x, y))
    if S[Dw][Dh].reached == True:
        break
    counter += 1
    for each in array:
        while len(each) > 0:
            i, j = each.pop()
            if S[i][j].reached and S[i][j].checked == False:
                jump(i, j, q)
    if len(q) == 0:
        flag = True
        break
if flag:
    print(-1)
else:
    print(counter)

Submission status: Time Limit Exceeded

Solution code:
"""
    Satwik_Tiwari ;) .
    21st AUGUST , 2020  - FRIDAY
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
  def wrapped_func(*args, **kwargs):
    if stack: return f(*args, **kwargs)
    to = f(*args, **kwargs)
    while True:
      if type(to) is GeneratorType:
        stack.append(to)
        to = next(to)
        continue
      stack.pop()
      if not stack: break
      to = stack[-1].send(to)
    return to
  return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
def djkistra(g,st,dist): #g contains b,dist(a to b) and dist is initiaalised by 10**9 initiallly
    pq = []
    dist[st] = 0
    pq.append([0,st])
    while(len(pq) != 0):
        curr = heappop(pq)[1]
        for i in range(0,len(g[curr])):
            b = g[curr][i][0]
            w = g[curr][i][1]
            if(dist[b] > dist[curr] + w):
                dist[b] = dist[curr]+w
                pq.append([dist[b],b])

def solve():
    n,m = sep()
    x,y = sep()
    xnot ,ynot = sep()
    x-=1
    y-=1
    xnot-=1
    ynot-=1

    grid = []
    for i in range(n):
        temp = list(inp())
        grid.append(temp)

    g = [[] for i in range(n*m)]

    for i in range(n):
        for j in range(m):
            if(grid[i][j] == '#'):
                continue
            for ii in range(i-2,i+3):
                for jj in range(j-2,j+3):
                    if(ii==i and jj==j):
                        continue
                    if(0<=ii<n and 0<=jj<m and grid[ii][jj] == '.'):
                        if(abs(ii-i)+abs(jj-j) == 1):
                            g[i*m+j].append((ii*m+jj,0))
                        else:
                            g[i*m+j].append((ii*m+jj,1))
                        # print(i*m+j,ii*m+jj)
    # for i in range(n*m):
    #     print(g[i])

    dist = [10**9]*(n*m)
    # print(x*m+y,xnot*m+ynot)
    djkistra(g,x*m+y,dist)
    # print(dist[xnot*m+ynot])
    # print(dist)
    if(dist[xnot*m+ynot] == 10**9):
        print(-1)
    else:
        print(dist[xnot*m+ynot])









testcase(1)
# testcase(int(inp()))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import exit

h,w=map(int,input().split())
sh,sw=map(lambda s: int(s)-1,input().split())
gh,gw=map(lambda s: int(s)-1,input().split())
s = [input() for _ in range(h)]
d = [[h*w] * w for _ in range(h)]
q = deque()
d[sh][sw] = 0
q.append((sw, sh, 0))
while len(q):
  p = q.popleft()
  if p[2] != d[p[1]][p[0]]:
    continue
  if p[0] == gw and p[1] == gh:
    print(d[gh][gw])
    exit(0)
  for dx in range(-2, 3):
    nx = p[0] + dx
    if nx < 0 or w <= nx:
      continue
    for dy in range(-2, 3):
      ny = p[1] + dy
      c = 0 if abs(dx) + abs(dy) == 1 else 1
      if dx == dy == 0 or ny < 0 or h <= ny or s[ny][nx] == '#' or d[ny][nx] <= d[p[1]][p[0]] + c:
        continue
      d[ny][nx] = d[p[1]][p[0]] + c
      np = (nx, ny, d[ny][nx])
      if c:
        q.append(np)
      else:
        q.appendleft(np)
print(-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import collections
import itertools

def main():
    input = sys.stdin.readline
    h, w = map(int, input().split())
    ch, cw = map(lambda x:int(x) - 1, input().split())
    dh, dw = map(lambda x:int(x) - 1, input().split())
    s = [list(input().rstrip()) for _ in range(h)]
    
    que = collections.deque()
    que.append((0, ch, cw))
    cost = [[-1] * w for _ in range(h)]
    cost[ch][cw] = 0
    
    while que:
        c, py, px = que.popleft()
        if cost[py][px] == -1:
            cost[py][px] = c
        
        for dy, dx in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
            ny, nx = py + dy, px + dx
            if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == "." and cost[ny][nx] == -1:
                que.appendleft((c, ny, nx))
        
        for ny, nx in itertools.product(range(py - 2, py + 3), range(px - 2, px + 3)):
            if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == "." and cost[ny][nx] == -1:
                que.append((c + 1, ny, nx))
    
    print(cost[dh][dw])

    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import deque

f_inf = float("inf")

# Input#
# n = int(input())
h, w = map(int, input().split())
c_h, c_w = map(int, input().split())
d_h, d_w = map(int, input().split())

grid = []

d = deque()


for i in range(h + 1):
    if i == 0:
        array_tmp = "#" * w
    else:
        array_tmp = str(input().strip())
    array_tmp = "#" + array_tmp
    grid.append(list(array_tmp))


grid[c_h][c_w] = 0

d.append((c_h, c_w))


def check(tar_h, tar_w):
    if tar_h > h or tar_h < 1:
        return -1
    if tar_w > w or tar_w < 1:
        return -1
    if grid[tar_h][tar_w] == ".":
        return f_inf
    if grid[tar_h][tar_w] == "#":
        return -1
    else:
        return grid[tar_h][tar_w]


while len(d) != 0:
    tar_h, tar_w = d.popleft()
    tar_num = grid[tar_h][tar_w]
    if tar_num == "#":
        continue

    for i in range(5):
        for j in range(5):
            if check(tar_h + i - 2, tar_w + j - 2) > tar_num:
                if (
                    (i == 2 and j == 1)
                    or (i == 2 and j == 3)
                    or (i == 1 and j == 2)
                    or (i == 3 and j == 2)
                ):
                    grid[tar_h + i - 2][tar_w + j - 2] = tar_num
                    d.appendleft((tar_h + i - 2, tar_w + j - 2))
                else:
                    grid[tar_h + i - 2][tar_w + j - 2] = tar_num + 1
                    d.append((tar_h + i - 2, tar_w + j - 2))

if check(d_h, d_w) == f_inf:
    ans = -1
else:
    ans = check(d_h, d_w)

print("{}".format(ans))