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

def f1(x,y,xa,ya):
    if reach[xa][ya] == -1 or reach[xa][ya] > reach[x][y]:
         if c[xa][ya] == ".":
            reach[xa][ya] = reach[x][y]
            r.append([xa,ya])
            q.append([xa,ya])

def f2(x,y,xa,ya):
    if 0 <= xa <= h+1 and 0 <= ya <= w+1:
    
        if reach[xa][ya] == -1 or reach[xa][ya] > reach[x][y] + 1:
            if c[xa][ya] == ".":
                reach[xa][ya] = reach[x][y] + 1
                q.append([xa,ya])

h,w = map(int,input().split())
cx, cy = map(int,input().split())
dx, dy = map(int,input().split())

c = [0]*(h+2)
for i in range(1,h+1):
    c[i] = [0] + list(input()) + [0]
c[0]  = [0]*(w+2)
c[-1] = [0]*(w+2)

reach = [[-1 for j in range(w+2)] for i in range(h+2)]
q = deque([])

reach[cx][cy] = 0
q.append([cx,cy])

ans = 0

while q:

    
    
    x,y = q.popleft()
    
    r = deque()
    r.append([x,y])
    while r:
        xx,yy = r.popleft()
        
        f1(xx,yy,xx-1,yy)
        f1(xx,yy,xx+1,yy)
        f1(xx,yy,xx,yy-1)
        f1(xx,yy,xx,yy+1)
    
    for i in range(-2,3):
        for j in range(-2,3):
            f2(x,y,x+i,y+j)


print(reach[dx][dy])

Submission status: Time Limit Exceeded

Solution code:
import time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
from math import *
from bisect import *
from heapq import *
from collections import *
import queue

def lcm(a, b):  
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)    

    def ints(self, a):  
        print(" ".join([str(_) for _ in a]))
    
    def intsNL(self, a):
        for _ in a:
            print(_)
    
    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

H, W = In.ints()

grid = [["." for j in range(W)] for i in range(H)]

C = In.ints()
C = (C[0]-1, C[1]-1)
D = In.ints()
D = (D[0]-1, D[1]-1)

for i in range(H):
    s = In.str()

    for j in range(W):
        grid[i][j] = s[j]    

#print(grid)

moves = [[0,1], [0,-1], [1,0], [-1,0]]
setnext = set()
setnow = set([(C[0], C[1])])
quenow = deque([(C[0], C[1])])

ans = 0
found = False
hadOne = True

while hadOne:
    hadOne=False
    while len(quenow)>0:
        hadOne=True
        now = quenow.popleft()

        for i in range(-2,3):
            for j in range(-2, 3):
                nex = (now[0]+i, now[1]+j)

                if 0<=nex[0]<H and 0<=nex[1]<W and grid[nex[0]][nex[1]]==".":
                    if nex not in setnext:
                        setnext.add(nex)                    

        for m in moves:
            nex = (now[0]+m[0], now[1]+m[1])

            if nex == D:
                found = True
                break

            if 0<=nex[0]<H and 0<=nex[1]<W and grid[nex[0]][nex[1]] == "." and nex not in setnow:
                quenow.append(nex)
                setnow.add(nex)
        
        if found:
            break
    
    if found:
        break
    
    ans += 1

    for el in setnext:
        if el==D:
            found=True
            break
        if el not in setnow:            
            setnow.add(el)
            quenow.append(el)
    
    if found:
        break


if found:
    Out.int(ans)
else:
    Out.int(-1)
######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    H, W = map(int, input().split())
    sh, sw = map(lambda x: int(x) - 1, input().split())
    gh, gw = map(lambda x: int(x) - 1, input().split())
    grid = [list(input().rstrip()) for _ in range(H)]

    maze = [[f_inf] * W for _ in range(H)]
    maze[sh][sw] = 0
    que = deque([[sh, sw]])
    while que:
        h, w = que.popleft()
        for dh, dw in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            next_h, next_w = h + dh, w + dw
            if next_h < 0 or next_h >= H or next_w < 0 or next_w >= W:
                continue
            if grid[next_h][next_w] == ".":
                if maze[next_h][next_w] > maze[h][w]:
                    maze[next_h][next_w] = maze[h][w]
                    que.append([next_h, next_w])
        for dh in range(-2, 3):
            for dw in range(-2, 3):
                next_h, next_w = h + dh, w + dw
                if next_h < 0 or next_h >= H or next_w < 0 or next_w >= W:
                    continue
                if grid[next_h][next_w] == ".":
                    if maze[next_h][next_w] > maze[h][w] + 1:
                        maze[next_h][next_w] = maze[h][w] + 1
                        que.append([next_h, next_w])
    print(maze[gh][gw] if maze[gh][gw] != f_inf else -1)


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
cy, cx = map(int, input().split())
dy, dx = map(int, input().split())
cy -= 1
cx -= 1
dy -= 1
dx -= 1

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

worps = [[float('inf')]*W for _ in range(H)]
used = [[False]*W for _ in range(H)]
q = deque([[cy, cx]])

worp = 0
while q:
    v = {}
    find = False
    while q:
        y, x = q.popleft()
        used[y][x] = True
        worps[y][x] = min(worps[y][x], worp)

        if y == dy and x == dx:
            find = True
            break

        for h in range(-2+y, 3+y):
            for w in range(-2+x, 3+x):
                if 0 <= h and h < H and 0 <= w and w < W and S[h][w] == "." and not used[h][w]:
                    v[(h, w)] = True

        for h, w in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
            ny, nx = y+h, x+w
            if 0 <= ny and ny < H and 0 <= nx and nx < W:
                if not used[ny][nx] and S[ny][nx] == ".":
                    q.append([ny, nx])

    if find:
        break
    worp += 1
    for h, w in v.keys():
        if not used[h][w]:
            q.append([h, w])
            used[h][w] = True

ans = worps[dy][dx]
if ans != float('inf'):
    print(ans)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())  # H行, W列
CY, CX = map(lambda x: int(x)-1, input().split())  # 魔法使いの初期値
DY, DX = map(lambda x: int(x)-1, input().split())  # 目的地
gridgraph = [input() for _ in range(H)]
# print(gridgraph)

q = deque()
q.append([CY, CX])  # スタート地点
# 各頂点について2*2の幅優先する？
INF = float("inf")
adjacent = [[1, 0], [0, 1], [-1, 0], [0, -1]]  # 上下左右
distant = [[INF]*W for _ in range(H)]
# print(distant)
# 更新されるなら追加
distant[CY][CX] = 0
while len(q):
    cy, cx = q.popleft()  # 現在位置
    # 壁に当たったらワープ開始
    for dy, dx in adjacent:
        # 新しい位置
        ny = cy+dy
        nx = cx+dx
        if ny < 0 or ny >= H or nx < 0 or nx >= W:
            continue
        # 道の場合
        if gridgraph[ny][nx] == ".":
            # 道の場合はコスト0で移動できる
            if distant[ny][nx] > distant[cy][cx]:
                distant[ny][nx] = distant[cy][cx]
                q.append([ny, nx])
        # 新しい移動先が壁の場合
        elif gridgraph[ny][nx] == "#":
            # 周囲5*5の道に+1で到達する
            for i in range(-2, 3, 1):
                for j in range(-2, 3, 1):
                    target_y, target_x = cy+i, cx+j
                    if target_y < 0 or target_y >= H or target_x < 0 or target_x >= W:
                        continue
                    else:
                        if gridgraph[target_y][target_x] == "." and distant[target_y][target_x] > distant[cy][cx]+1:
                            distant[target_y][target_x] = distant[cy][cx]+1
                            q.append([target_y, target_x])
if distant[DY][DX] == INF:
    print(-1)
else:
    print(distant[DY][DX])

# print(distant)

Submission status: Time Limit Exceeded

Solution code:
import heapq
h,w = map(int, raw_input().split())
s = tuple(map(lambda x:int(x)-1 , raw_input().split()))
t = tuple(map(lambda x:int(x)-1 , raw_input().split()))

mat = [raw_input() for _ in range(h)]

def neighbors(u,mat):
	ret = []
	for i in [-2,-1,0,+1,+2]:
		for j in [-2,-1,0,+1,+2]:
			v= (u[0]+i,u[1]+j)
			if 0<=v[0]< len(mat) and 0<=v[1]< len(mat[0]) and mat[v[0]][v[1]] == '.':
				if v != u:
					ret.append(v)
	return ret
def f(s,t,mat):

	heap = [(0,s)]
	r = {} 
	while(heap):
		d,u = heapq.heappop(heap)
		if u in r and d > r[u]: continue
		r[u] = min(r[u] if u in r else +float('inf'), d)
		if u == t:
			return d

		for v in [(u[0],u[1]-1),(u[0]-1,u[1]),(u[0]+1,u[1]),(u[0],u[1]+1)]:
			if 0 <= v[0] < h and 0 <= v[1] < w and mat[v[0]][v[1]] == '.':
				if (v not in r) or r[v] > d:
					heapq.heappush(heap,(d,v))
					r[v] = d
		for v in neighbors(u,mat):
			
			if 0 <= v[0] < h and 0 <= v[1] < w:
				if (v not in r) or r[v] > d:
					heapq.heappush(heap,(d+1,v))
					r[v] = d + 1
	return -1
print f(s,t,mat)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys

def input():
    return sys.stdin.readline().strip()

def main():
    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)]
    S[Ch-1][Cw-1] = 0

    def bfs(x,y):
        que = deque()
        que.append((x,y))

        while que:
            x,y = que.popleft()
            for dx in range(-2,3):
                for dy in range(-2,3):
                    sx = x + dx
                    sy = y + dy
                    if sx < 0 or sx >= W or sy < 0 or sy >= H:
                        continue
                    if S[sy][sx] == '#':
                        continue
                    if (dx,dy) in ((-1,0),(1,0),(0,-1),(0,1)):
                        cnt = 0
                    else:
                        cnt = 1
                    if S[sy][sx] == '.':
                        que.append((sx,sy))
                        S[sy][sx] = S[y][x] + cnt
                    elif S[sy][sx] > S[y][x] + cnt:
                        S[sy][sx] = S[y][x] + cnt
                        que.append((sx,sy))
    bfs(Cw-1,Ch-1)
    print(S[Dh-1][Dw-1] if S[Dh-1][Dw-1] != '.' else '-1')

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

H,W = map(int,readline().split())
sh,sw = map(int,readline().split())
gh,gw = map(int,readline().split())

maze = []
for _ in range(H):
    res = [-1]*W
    s = readline().rstrip().decode('utf-8')
    for i in range(W):
        if s[i] == ".":
            res[i] = 0
    maze.append(res)
    #maze += [list(readline().rstrip().decode().replace(".",0).replace("#",-1))]
    

ct = 1
for h in range(H):
    for w in range(W):
        if maze[h][w] == 0:
            y,x = h,w
            maze[y][x] = ct
            stack = deque([[y,x]])
            while stack:
                i,j = stack.pop()
                for ni,nj in [(0,1),(1,0),(0,-1),(-1,0)]:
                    if not 0 <= i + ni < H or not 0 <= j + nj < W:
                        continue
                    if maze[i+ni][j+nj] == 0:
                        maze[i+ni][j+nj] = ct
                        stack.append([i+ni,j+nj])
            ct += 1

g = [[] for i in range(ct)]
g2 = [[0]*ct for _ in range(ct)]
for i in range(ct):
    g2[i][i] = 1
for h in range(H):
        for w in range(W):
            if maze[h][w] != -1:
                for i,j in [(-1,-2),(-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),(-1,2),(0,2)]:
                        if not 0 <= i + h < H or not 0 <= j + w < W:
                            continue
                        if maze[h+i][w+j] != -1 and \
                            not g2[maze[h][w]][maze[h+i][w+j]]:
                            g[maze[h][w]].append((1,maze[h+i][w+j]))
                            g[maze[h+i][w+j]].append((1,maze[h][w]))
                            g2[maze[h][w]][maze[h+i][w+j]] = 1
                            g2[maze[h+i][w+j]][maze[h][w]] = 1


#ダイクストラ法通常版
#O(ElogV)
import heapq
def dijkstra_heap(s,edge): #s:始点,g:グラフ
    #始点sから各頂点への最短距離
    d = [float("inf")] * len(edge)
    used = [True] * len(edge) #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge[1]]: #既に最小距離が確定しているなら
            continue
        v = minedge[1] #vに頂点を代入
        d[v] = minedge[0] #その頂点のコストに重みを代入
        used[v] = False #vには最小距離が入っていることが証明できる(ヒープキューを使用しているため)
        for e in edge[v]: #頂点vから伸びている辺の先をヒープキューに入れてく
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v],e[1]))
    return d #回しきったらreturn(たどり着けなかった頂点はinf.)


start = maze[sh-1][sw-1]
goal = maze[gh-1][gw-1]

res = dijkstra_heap(start,g)

if res[goal] == float("inf"):
    print(-1)
else:
    print(res[goal])

Submission status: Time Limit Exceeded

Solution code:
from pprint import pprint
from collections import deque
def LI():
    return list(map(int,input().split()))
INF=float("inf")

h,w=LI()
ch,cw=LI()
# ch-=1
# cw-=1
dh,dw=LI()
# dh-=1
# dw-=1

maze=[list("#"*(w+2))]+[list("#"+input()+"#") for i in range(h)]+[list("#"*(w+2))]
# S=[input() for _ in range(h)]

visited=[[False]*(w+2) for _ in range(h+2)]

q=deque()
q.append((ch,cw))
p=deque()
while q:
    x,y=q.popleft()
    visited[x][y]=True
    for i,j in ((-1,0),(1,0),(0,1),(0,-1)):
        xn,yn=x+i,y+j
        if maze[xn][yn]=="." and visited[xn][yn]==False:
            visited[xn][yn]=True
            q.append((xn,yn))
    for i in range(-2,3,1):
        for j in range(-2,3,1):
            xm,ym=x+i,y+j
            try:
                if visited[xm][ym]==False:
                    if maze[xm][ym]==".":
                        p.append((xm,ym))
            except:pass
if visited[dh][dw]==True:
    print(0)
    exit()

for pp in p:
    if visited[pp[0]][pp[1]]==False:
        q.append(pp)
if len(q)==0:
    print(-1)
    exit()
for ttt in range(1,100000):
    while q:
        x,y=q.popleft()
        visited[x][y]=True
        for i,j in ((-1,0),(1,0),(0,1),(0,-1)):
            xn,yn=x+i,y+j
            if maze[xn][yn]=="." and visited[xn][yn]==False:
                visited[xn][yn]=True
                q.append((xn,yn))
        for i in range(-2,3,1):
            for j in range(-2,3,1):
                xm,ym=x+i,y+j
                try:
                    if visited[xm][ym]==False:
                        if maze[xm][ym]==".":
                            p.append((xm,ym))
                except:pass
    
    if visited[dh][dw]==True:
        print(ttt)
        exit()
        
    for pp in p:
        if visited[pp[0]][pp[1]]==False:
            q.append(pp)
    if len(q)==0:
        print(-1)
        exit()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


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
rows,cols = h,w

OK = "."
NG = "#"

from collections import defaultdict

ns = defaultdict(set)
ss = [None] * rows
for i in range(rows):
    s = input()
    ss[i] = s
n = rows * cols
start = (ch,cw)
goal = (dh,dw)
seen = [None]*n
seen[start[0]*w+start[1]] = 0
from heapq import heappop as hpp, heappush as hp
q = [(0, start)] # ワープ回数, 現在位置, 最後の道の位置
# dx = [0,1,0,-1]
# dy = [1,0,-1,0]
dx = []
dy = []
vvs = []
for i in range(-2,3):
    for j in range(-2,3):
        if not (i==j==0):
            dx.append(i)
            dy.append(j)
            if abs(i)+abs(j)>1:
                vvs.append(1)
            else:
                vvs.append(0)
while q:
    pnum,(ux,uy) = hpp(q)
#     print(ux,uy, num, prv)
    for xx,yy,vv in zip(dx,dy,vvs):
        x = ux+xx
        y = uy+yy
        num = pnum+vv
        if x<0 or y<0 or x>=h or y>=w or ss[x][y]=="#":
            continue            
        if seen[x*w+y] is None or seen[x*w+y]>num:
            seen[x*w+y] = num
            hp(q, (num, (x,y)))
val = seen[goal[0]*w+goal[1]]
if val is None:
    print(-1)
else:
    print(val)

Submission status: Time Limit Exceeded

Solution code:
h, w = [int(i) for i in input().split()]
ch, cw = [int(i) for i in input().split()]
ch -= 1
cw -= 1
dh, dw = [int(i) for i in input().split()]
dh -= 1
dw -= 1

loc = []
move = []
checked = []
magicchecked = []
for i in range(h):
    line = input()
    loc.append([j for j in line])
    move.append([-1 for j in line])
    checked.append([0 for j in line])
    magicchecked.append([0 for j in line])

move[ch][cw] = 0
cur = 0
walk = [(ch, cw)]
magic = []
while len(walk) > 0:
    node = walk.pop()
    checked[node[0]][node[1]] = 1
    if node[0] - 1 >= 0 and loc[node[0] - 1][node[1]] != "#" and checked[node[0] - 1][node[1]] == 0:
        walk.append((node[0] - 1, node[1]))
    if node[1] - 1 >= 0 and loc[node[0]][node[1] - 1] != "#" and checked[node[0]][node[1] - 1] == 0:
        walk.append((node[0], node[1] - 1))
    if node[0] + 1 < h and loc[node[0] + 1][node[1]] != "#" and checked[node[0] + 1][node[1]] == 0:
        walk.append((node[0] + 1, node[1]))
    if node[1] + 1 < w and loc[node[0]][node[1] + 1] != "#" and checked[node[0]][node[1] + 1] == 0:
        walk.append((node[0], node[1] + 1))
    move[node[0]][node[1]] = cur


for i in range(h):
    for j in range(w):
        if loc[i][j] == "." and checked[i][j] == 1:
            for k in range(-2, 3):
                for l in range(-2, 3):
                    if i + k >= 0 and i + k < h and j + l >= 0 and j + l < w \
                    and loc[i + k][j + l] == "." and checked[i + k][j + l] == 0 and magicchecked[i + k][j + l] == 0:
                        magicchecked[i + k][j + l] = 1
                        magic.append((i + k, j + l))

cur += 1

while magic:
    walk = magic[:]
    magic = []

    while len(walk) > 0:
        node = walk.pop()
        checked[node[0]][node[1]] = 1
        if node[0] - 1 >= 0 and loc[node[0] - 1][node[1]] != "#" and checked[node[0] - 1][node[1]] == 0:
            walk.append((node[0] - 1, node[1]))
        if node[1] - 1 >= 0 and loc[node[0]][node[1] - 1] != "#" and checked[node[0]][node[1] - 1] == 0:
            walk.append((node[0], node[1] - 1))
        if node[0] + 1 < h and loc[node[0] + 1][node[1]] != "#" and checked[node[0] + 1][node[1]] == 0:
            walk.append((node[0] + 1, node[1]))
        if node[1] + 1 < w and loc[node[0]][node[1] + 1] != "#" and checked[node[0]][node[1] + 1] == 0:
            walk.append((node[0], node[1] + 1))
        move[node[0]][node[1]] = cur

    for i in range(h):
        for j in range(w):
            if loc[i][j] == "." and checked[i][j] == 1:
                for k in range(-2, 3):
                    for l in range(-2, 3):
                        if i + k >= 0 and i + k < h and j + l >= 0 and j + l < w \
                        and loc[i + k][j + l] == "." and checked[i + k][j + l] == 0 and magicchecked[i + k][j + l] == 0:
                            magicchecked[i + k][j + l] = 1
                            magic.append((i + k, j + l))


    cur += 1

print(move[dh][dw])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def solvemaze(y, x, num):
    maps.append([])
    dx, dy = (-1, 0, 1, 0), (0, -1, 0, 1)
    maze[y][x] = num
    que = deque()
    que.append((y, x))
    while que:
        y_, x_ = que.popleft()
        maps[num].append((y_, x_))
        for i in range(4):
            y2 = y_ + dy[i]
            x2 = x_ + dx[i]
            if 0 <= y2 < h and 0 <= x2 < w and maze[y2][x2] == '.':
                maze[y2][x2] = num
                que.append((y2, x2))

def makeroute(s_maps, num):
    res = []
    for y, x in s_maps:
        for i in range(-2, 3):
            for j in range(-2, 3):
                y2 = y + i
                x2 = x + j
                if 0 <= y2 < h and 0 <= x2 < w and not maze[y2][x2] in (num,'#') and not maze[y2][x2] in res:
                    res.append(maze[y2][x2])
    
    return res
        

def dijkstra(s, g):
    que = deque()
    d = [float('inf')] * num
    d[s] = 0
    que.append((0, s))
    while que:
        cost, v = que.popleft()
        if d[v] < cost:
            continue
        for i in range(len(E[v])):
            e = E[v][i]
            if d[e] > d[v] + 1:
                d[e] = d[v] + 1
                que.append((d[e], e))
    
    if d[g] == float('inf'):
        return -1
    return d[g]
    

h, w = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [[x for x in input()] for _ in range(h)]
maps = []

num = 0
for i in range(h):
    for j in range(w):
        if maze[i][j] == '.':
            solvemaze(i, j, num)
            num += 1

E = [[] for _ in range(num)]
for i in range(num):
    E[i] = makeroute(maps[i], i)

s = maze[Ch-1][Cw-1]
g = maze[Dh-1][Dw-1]
print(dijkstra(s, g))

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
nx,ny=map(int,input().split())
gx,gy=map(int,input().split())
maze=[input()for i in range(h)]
from heapq import heapify, heappop, heappush
seen=set()
gx-=1;gy-=1
SIZE=h*w
hq=[(nx-1)*w+ny-1]
while hq:
    d=heappop(hq)
    c,d=divmod(d,SIZE)
    x,y=divmod(d,w)
    if w*x +y in seen:continue
    seen.add(w*x +y)
    if x==gx and y==gy:print(c);exit()
    if x and w*(x-1)+y not in seen and maze[x-1 ][y]!="#":
        heappush(hq,(c*SIZE+w*(x-1)+y))
    if y and w*x+y-1 not in seen and maze[x][y-1]!="#":
        heappush(hq,(c*SIZE+w*x+y-1))
    if x+1<h  and w*(x+1)+y not in seen and maze[x+1][y]!="#":
        heappush(hq,(c*SIZE+w*(x+1)+y))
    if y+1<w  and w*x+y+1 not in seen and maze[x][y+1]!="#":
        heappush(hq,(c*SIZE+w*x+y+1))
    for i in range(max(0,x-2),min(h,x+3)):
        for j in range(max(0,y-2),min(w,y+3)):
            if i==x and j==y:continue
            if maze[i][j]=="."and w*i + j not in seen:
                heappush(hq,(c+1)*SIZE+w*i+j)

print(-1)

Submission status: Time Limit Exceeded

Solution code:
# import sys
# input = sys.stdin.readline

def mp(): return map(int, input().split())
def lmp(): return list(map(int, input().split()))

h,w = mp()
ch, cw = mp()
dh,dw = mp()
ch += 1
cw += 1
dh += 1
dw += 1
grid = []
grid.append(["#"]*(w+4))
grid.append(["#"]*(w+4))
ans_grid = []
for i in range(h):
    u = ["#", "#"]
    a = list(input())
    for j in range(w):
        u.append(a[j])
    u.append("#")
    u.append("#")
    grid.append(u)
grid.append(["#"]*(w+4))
grid.append(["#"]*(w+4))

for i in range(h+4):
    ans_grid.append([int(1e8)]*(w+4))
# print(grid)
# print(ans_grid)

from collections import deque
def bfs(x,y):
    q = deque([])
    used = set()
    q.append((x,y))
    used.add((x,y))
    ans_grid[x][y] = 0
    while q:
        here = q.popleft()
        move = [(here[0]-1, here[1]),
                (here[0], here[1]-1),
                (here[0], here[1]+1),
                (here[0]+1, here[1])]
        warp = [(here[0]-2, here[1]-2), (here[0]-2, here[1]-1), (here[0]-2, here[1]), (here[0]-2, here[1]+1), (here[0]-2, here[1]+2),
                (here[0]-1, here[1]-2), (here[0]-1, here[1]-1), (here[0]-1, here[1]), (here[0]-1, here[1]+1), (here[0]-1, here[1]+2),
                (here[0], here[1]-2), (here[0], here[1]-1), (here[0], here[1]+1), (here[0], here[1]+2),
                (here[0]+1, here[1]-2), (here[0]+1, here[1]-1), (here[0]+1, here[1]), (here[0]+1, here[1]+1), (here[0]+1, here[1]+2),
                (here[0]+2, here[1]-2), (here[0]+2, here[1]-1), (here[0]+2, here[1]), (here[0]+2, here[1]+1), (here[0]+2, here[1]+2),]
        for i in range(len(warp)):
            u = warp[i][0]
            v = warp[i][1]
            if grid[u][v] == "." and ans_grid[u][v] >= ans_grid[here[0]][here[1]]+1:
                ans_grid[u][v] = min(ans_grid[u][v], ans_grid[here[0]][here[1]]+1)
                q.append((u,v))
        #print(q)
        for i in range(len(move)):
            u = move[i][0]
            v = move[i][1]
            if move[i] not in used and grid[u][v] == ".":
                ans_grid[u][v] = min(ans_grid[here[0]][here[1]], ans_grid[u][v])
                q.append((u,v))
                used.add((u,v))


bfs(ch,cw)
ans = ans_grid[dh][dw]
#print(ans_grid)
if ans == int(1e8):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
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()))
maze = [[int(ch == '#') for ch in input().rstrip()] for _ in range(H)]

from sys import exit
from collections import deque
from itertools import product
que = deque([c])
passed = set()
queued = set()
nque = set()
cnt = 0
while nque or que:
    while que:
        h,w = que.popleft()
#         print(f'{h=},{w=}')
        if (h,w) == d:
            print(cnt)
            exit()
        if (h,w) in passed:
            continue
        passed.add((h,w))
        for dh, dw in [[0,1], [0,-1], [1,0], [-1,0]]:
            nh = h + dh
            nw = w + dw
            if 0 <= nh < H and 0 <= nw < W and (nh,nw) not in passed and (nh,nw) not in queued and not maze[nh][nw]:
#                 print(f'no_warp: {nh=},{nw=}')
                que.append((nh,nw))
                queued.add((nh,nw))
                nque.discard((nh,nw))

        for dh,dw in product(range(-2, 3), repeat=2):
            if [dh,dw] in [[0,0], [0,1], [0,-1], [1,0], [-1,0]]:
                continue
            nh = h + dh
            nw = w + dw
            if 0 <= nh < H and 0 <= nw < W and (nh,nw) not in passed and (nh,nw) not in queued and not maze[nh][nw]:
#                 print(f'warp: {nh=},{nw=}')
                nque.add((nh,nw))
    que = deque(nque)
    nque = set()
    cnt += 1
#     print(f'{que=}, {cnt=}')
print(-1)