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

# import sys

# input = sys.stdin.readline
# sys.setrecursionlimit(10 ** 7)


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Ch -= 1
    Cw -= 1
    Dh, Dw = map(int, input().split())
    Dh -= 1
    Dw -= 1
    S = []
    S.append(["#"] * (4 + W))
    S.append(["#"] * (4 + W))
    for i in range(H):
        S.append(["#", "#"] + list(input()) + ["#", "#"])
    S.append(["#"] * (4 + W))
    S.append(["#"] * (4 + W))
    dist = [[10 ** 18] * (4 + W) for _ in range(H + 4)]
    # print(S, warp)

    def bfs(i, j):
        q = deque()
        q.append((i, j))
        dist[i][j] = 0
        while q:
            a, b = q.popleft()
            for x in range(-2, 3):
                for y in range(-2, 3):
                    if S[a + x][b + y] == ".":
                        warp = abs(x) + abs(y) != 1
                        d = dist[a][b] + int(warp)
                        if d < dist[a + x][b + y]:
                            dist[a + x][b + y] = d
                            if warp:
                                q.append((a + x, b + y))
                            else:
                                q.appendleft((a + x, b + y))
                            # print(q)

    bfs(Ch + 2, Cw + 2)
    if dist[Dh + 2][Dw + 2] == 10 ** 18:
        print(-1)
    else:
        print(dist[Dh + 2][Dw + 2])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def idx(h,w):
    return h*W + w

def main():
    adj=[(-1,0), (0,1), (1,0), (0,-1)]
    graph=[set() for _ in range(N)]
    for h in range(H):
        for w in range(W):
            idx_from=idx(h,w)
            if Ss[h][w]=='#':
                continue
            for dh in range(-2,3):
                for dw in range(-2,3):
                    if dh==0 and dw==0:
                        continue
                    h_dst=h+dh
                    w_dst=w+dw
                    
                    if (0<=h_dst<H) and (0<=w_dst<W) and (Ss[h_dst][w_dst]=='.'):
                        idx_to=idx(h_dst,w_dst)
                        if (dh,dw) in adj:
                            graph[idx_from].add((idx_to,0))
                            #graph[idx_to].add((idx_from,0))
                        else:
                            graph[idx_from].add((idx_to,1))
                            #graph[idx_to].add((idx_from,1))
    s=idx(Ch,Cw)
    dist=[10**9]*N
    dist[s]=0
    que=deque()
    que.append(s)

    while len(que)>0:
        i = que.popleft() # 先頭取り出し
        for j,c in graph[i]:
            d = dist[i] + c
            if d < dist[j]:
                dist[j] = d
                if c == 1:
                    que.append(j) # 末尾へ
                else:
                    que.appendleft(j) #先頭へ
    #print(graph,dist)
    ans = dist[idx(Dh,Dw)]
    print(-1 if ans == 10**9 else ans)

H,W=map(int,input().split())
N=H*W
Ch,Cw=[int(e)-1 for e in input().split()]
Dh,Dw=[int(e)-1 for e in input().split()]
Ss=[]
for _ in range(H):
    #Ss.append([(1 if c=='.'else 0) for c in input()])
    Ss.append(input())
main()

Submission status: Time Limit Exceeded

Solution code:
import math
from collections import deque, defaultdict

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 = [[char for char in input()] for _ in range(h)]
# print(f'{s=}')

queue, visited = deque([[(ch, cw), 0]]), defaultdict(bool)

while queue:
	pos, magic_count = queue.popleft()
	x, y = pos

	# print(f'{pos=} {magic_count=} {queue=} {visited[pos]=}')

	if pos == (dh, dw):
		print(magic_count)
		break


	if not visited[pos]:
		visited[pos] = True
	
		for dx, dy in [(i, j) for i in range(-2, 3) for j in range(-2, 3)]:
			# print(f'{dx=} {dy=}')
			xx, yy = x + dx, y + dy
			# print(f'{xx=} {yy=}')

			if xx < 0 or xx >= h or yy < 0 or yy >= w:
				continue

			if s[xx][yy] == '.' and not visited[(xx, yy)]:
				if math.hypot(dx, dy) == 1:
					queue.appendleft(((xx, yy), magic_count))
				else:
					queue.append(((xx, yy), magic_count + 1))

else:
	print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def main():
    movey = (0, -1, 0, 1)
    movex = (1, 0, -1, 0)
    warpy = (-2, -2, -2, -2, -2, -1, -1, -1, -1,  0, 0,  1,  1, 1, 1, 2, 2, 2, 2, 2)
    warpx = (-2, -1,  0,  1,  2, -2, -1,  1,  2, -2, 2, -2, -1, 1, 2, -2, -1, 0, 1, 2)

    h, w = map(int, input().split())
    ch, cw = map(int, input().split())
    dh, dw = map(int, input().split())
    ch += 1
    cw += 1
    dh += 1
    dw += 1
    dummy = tuple(['#'] * (w + 4))
    maze = {e: [] for e in range(h + 4)}
    maze[0] = dummy
    maze[1] = dummy
    for i in range(h):
        row = ['#'] + ['#'] + list(input()) + ['#'] + ['#']
        maze[i+2] = row
    maze[h+2] = dummy
    maze[h+3] = dummy
    maze[ch][cw] = 0
    maze[dh][dw] = 'g'

    nodes = deque()
    nodes.append((ch, cw))
    res = []
    while nodes:
        (n_y, n_x) = nodes.popleft()
        cur_masu = maze[n_y][n_x]
        flag = False
        for j1 in range(4):
            ny = n_y + movey[j1]
            nx = n_x + movex[j1]
            next_masu = maze[ny][nx]
            if next_masu == 'g':
                res.append(cur_masu)
            elif next_masu == '.':
                maze[ny][nx] = cur_masu
                nodes.appendleft((ny, nx))
            elif next_masu == '#':
                flag = True
            elif next_masu > cur_masu:
                maze[ny][nx] = cur_masu
                nodes.appendleft((ny, nx))
        if flag:
            for j1 in range(20):
                ny = n_y + warpy[j1]
                nx = n_x + warpx[j1]
                next_masu = maze[ny][nx]
                if next_masu == 'g':
                    res.append(cur_masu+1)
                elif next_masu == '.':
                    maze[ny][nx] = cur_masu + 1
                    nodes.append((ny, nx))
                elif next_masu == '#':
                    pass
                elif next_masu > cur_masu + 1:
                    maze[ny][nx] = cur_masu + 1
                    nodes.append((ny, nx))

    if res:
        print(min(res))
    else:
        print(-1)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import collections, itertools

h, w = map(int, input().split())
ch, cw = tuple(int(s) - 1 for s in input().split())
dh, dw = tuple(int(s) - 1 for s in input().split())
s = [input() for _ in range(h)]

q = collections.deque()
q.append((ch, cw, 0))
score = [[float('inf')] * w for _ in range(h)]
score[ch][cw] = 0
while q:
    x, y, p = q.popleft()

    for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and p < score[nx][ny]:
            score[nx][ny] = p
            q.appendleft((nx, ny, p))
    
    for dx, dy in itertools.product(range(-2, 3), repeat=2):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and p + 1 < score[nx][ny]:
            score[nx][ny] = p + 1
            q.append((nx, ny, p + 1))

if score[dh][dw] == float('inf'):
    print(-1)
else:
    print(score[dh][dw])

Submission status: Time Limit Exceeded

Solution code:
import collections, itertools

h, w = map(int, input().split())
ch, cw = tuple(int(s) - 1 for s in input().split())
dh, dw = tuple(int(s) - 1 for s in input().split())
s = [input() for _ in range(h)]

q = collections.deque()
q.append((ch, cw))
score = [[float('inf')] * w for _ in range(h)]
score[ch][cw] = 0
while q:
    x, y = q.popleft()

    for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and score[x][y] < score[nx][ny]:
            score[nx][ny] = score[x][y]
            q.appendleft((nx, ny))
    
    for dx, dy in itertools.product(range(-2, 3), repeat=2):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and score[x][y] + 1 < score[nx][ny]:
            score[nx][ny] = score[x][y] + 1
            q.append((nx, ny))

if score[dh][dw] == float('inf'):
    print(-1)
else:
    print(score[dh][dw])

Submission status: Time Limit Exceeded

Solution code:
import math
from collections import deque, defaultdict

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 = [[char for char in input()] for _ in range(h)]
# print(f'{s=}')

queue, visited = deque([[(ch, cw), 0]]), set()

while queue:
	pos, magic_count = queue.popleft()
	x, y = pos

	# print(f'{pos=} {magic_count=} {queue=} {visited=}')
	# print(f'{x=} {y=}')


	if pos == (dh, dw):
		print(magic_count)
		break


	if pos not in visited:
		visited.add(pos)
	
		for dx, dy in [(i, j) for i in range(-2, 3) for j in range(-2, 3)]:
			# print(f'{dx=} {dy=}')
			xx, yy = x + dx, y + dy
			# print(f'{xx=} {yy=}')
			# if x == 1 and y == 0:
			# 	print(xx, yy)

			if xx < 0 or xx >= h or yy < 0 or yy >= w:
				continue

			if s[xx][yy] == '.' and (xx,yy) not in visited:
				if math.hypot(dx, dy) == 1:
					queue.appendleft(((xx, yy), magic_count))
					# visited[(xx, yy)] = min(visited[(xx, yy)], magic_count)
				else:
					queue.append(((xx, yy), magic_count + 1))
					# visited[(xx, yy)] = min(visited[(xx, yy)], magic_count+1)

else:
	print(-1)

Submission status: Time Limit Exceeded

Solution code:
import collections, itertools

h, w = map(int, input().split())
ch, cw = tuple(int(s) - 1 for s in input().split())
dh, dw = tuple(int(s) - 1 for s in input().split())
s = [input() for _ in range(h)]

q = collections.deque()
q.append((ch, cw))
score = [[float('inf')] * w for _ in range(h)]
score[ch][cw] = 0
while q:
    x, y = q.popleft()

    for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and score[x][y] < score[nx][ny]:
            score[nx][ny] = score[x][y]
            q.append((nx, ny))
    
    for dx, dy in itertools.product(range(-2, 3), repeat=2):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and score[x][y] + 1 < score[nx][ny]:
            score[nx][ny] = score[x][y] + 1
            q.append((nx, ny))

if score[dh][dw] == float('inf'):
    print(-1)
else:
    print(score[dh][dw])

Submission status: Time Limit Exceeded

Solution code:
import math
from collections import deque, defaultdict

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 = [[char for char in input()] for _ in range(h)]
# print(f'{s=}')

queue, visited = deque([[(ch, cw), 0]]), set()

while queue:
	pos, magic_count = queue.popleft()
	x, y = pos

	# print(f'{pos=} {magic_count=} {queue=} {visited=}')
	# print(f'{x=} {y=}')


	if pos == (dh, dw):
		print(magic_count)
		break


	if pos not in visited:
		visited.add(pos)
	
		for dx, dy in [(i, j) for i in range(-2, 3) for j in range(-2, 3)]:
			# print(f'{dx=} {dy=}')
			xx, yy = x + dx, y + dy
			# print(f'{xx=} {yy=}')
			# if x == 1 and y == 0:
			# 	print(xx, yy)

			if xx < 0 or xx >= h or yy < 0 or yy >= w:
				continue

			if s[xx][yy] == '.':
				if math.hypot(dx, dy) == 1:
					queue.appendleft(((xx, yy), magic_count))
					# visited[(xx, yy)] = min(visited[(xx, yy)], magic_count)
				else:
					queue.append(((xx, yy), magic_count + 1))
					# visited[(xx, yy)] = min(visited[(xx, yy)], magic_count+1)

else:
	print(-1)

Submission status: Time Limit Exceeded

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

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

visit=defaultdict(lambda: 0) #0:未訪問、1:訪問済み
d=defaultdict(lambda: float("inf")) #スタート地点から各マスまでの距離

q=deque()
q.append((CH,CW))
d[(CH,CW)]=0

while q:
    fro_h, fro_w=q.popleft()
    kyori=d[(fro_h, fro_w)]
    #print "kyori,fro_h, fro_w, q :: ",kyori, fro_h, fro_w, q
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]<d[(to_h, to_w)] and visit[(to_h, to_w)]==0:
            visit[(to_h, to_w)]==1
            d[(to_h, to_w)]=d[(fro_h, fro_w)]
            q.appendleft((to_h, to_w))

    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]+1<d[(to_h, to_w)] and visit[(to_h, to_w)]==0:
            visit[(to_h, to_w)]==1
            d[(to_h, to_w)]=d[(fro_h, fro_w)]+1
            q.append((to_h, to_w))

if d[(DH,DW)]==float("inf"):
    print -1
else:
    print d[(DH,DW)]

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def idx(h,w):
    return h*W + w

def main():
    graph=[set() for _ in range(N)]
    for h in range(H):
        for w in range(W):
            idx_from=idx(h,w)
            if Ss[h][w]==0:
                continue
            adj=[(-1,0), (0,1), (1,0), (0,-1)]
            for dh in [-2,-1, 0, 1, 2]:
                for dw in [-2, -1, 0, 1, 2]:
                    h_dst=h+dh
                    w_dst=w+dw
                    if (0<=h_dst<H) and (0<=w_dst<W) and (dh!=0 or dw!=0) and (Ss[h_dst][w_dst]==1):
                        idx_to=idx(h_dst,w_dst)
                        if (dh,dw) in adj:
                            graph[idx_from].add((idx_to,0))
                            graph[idx_to].add((idx_from,0))
                        else:
                            graph[idx_from].add((idx_to,1))
                            graph[idx_to].add((idx_from,1))
    s=idx(Ch,Cw)
    dist=[10**9]*N
    dist[s]=0
    que=deque()
    que.append(s)

    while len(que)>0:
        i = que.popleft() # 先頭取り出し
        for j,c in graph[i]:
            d = dist[i] + c
            if d < dist[j]:
                dist[j] = d
                if c == 1:
                    que.append(j) # 末尾へ
                else:
                    que.appendleft(j) #先頭へ
    #print(graph,dist)
    ans = dist[idx(Dh,Dw)]
    print(-1 if ans == 10**9 else ans)

H,W=map(int,input().split())
N=H*W
Ch,Cw=[int(e)-1 for e in input().split()]
Dh,Dw=[int(e)-1 for e in input().split()]
Ss=[]
for _ in range(H):
    Ss.append([(1 if c=='.'else 0) for c in input()])
main()

Submission status: Time Limit Exceeded

Solution code:
import queue

def is_not_road(x, y):
    return x < 0 or x >= h or y < 0 or y >= w or m[x][y] < 0

def put_if(q, x, y, c):
    if is_not_road(x, y) or m[x][y] > 0 and m[x][y] <= c:
        return
    q.put((x, y, c))

m = []
q = queue.Queue()

h, w = list(map(int, input().split()))
cx, cy = list(map(lambda c: int(c) - 1, input().split()))
dx, dy = list(map(lambda c: int(c) - 1, input().split()))

for _ in range(h):
    s = input()
    m.append([0 if c == '.' else -1 for c in s])

q.put((cx, cy, 1))

while not q.empty():
    x, y, c = q.get()
    m[x][y] = c

    put_if(q, x - 1, y, c)
    put_if(q, x + 1, y, c)
    put_if(q, x, y - 1, c)
    put_if(q, x, y + 1, c)

    for i in range(-2, 3):
        for j in range(-2, 3):
            if abs(i) + abs(j) <= 1: continue
            put_if(q, x + i, y + j, c + 1)

if m[dx][dy] > 0:
    print(m[dx][dy] - 1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int,input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
c = [["#"]*(W+4) for _ in range(H+4)]
for y in range(H):
    c[y+2] = *list("##"+input()+"##"), 
inf = H*W
m = [[inf]*W for _ in range(H)]
m[ch-1][cw-1] = 0
drs = [[-1,0],[1,0],[0,0],[0,-1],[0,1]]
warps = [[-2,-2],[-2,-1],[-2,0],[-2,1],[-2,2],
        [2,-2],[2,-1],[2,0],[2,1],[2,2],
        [-1,-2],[0,-2],[1,-2],
        [-1,2],[0,2],[1,2],
        [-1,-1],[-1,1],[1,-1],[1,1]
       ]

s = 0
yx = [[ch+1, cw+1]]
notgoal = True
yxwarp = True
while notgoal and yxwarp:
    yxwarp = []
    while yx:
        yx2 = []
        for y,x in yx:
            for dy, dx in drs:
                x2 = x+dx
                y2 = y+dy
                if c[y2][x2] == "." and m[y2-2][x2-2] == inf:
                    m[y2-2][x2-2] = s
                    if (y2,x2) == (dh+1,dw+1):
                        notgoal = False
                        break
                    else:
                        yx2.append([y2, x2])
                        continue
                    break
            for dy, dx in warps:
                x2 = x+dx
                y2 = y+dy
                if c[y2][x2] == "." and m[y2-2][x2-2] == inf:
                    yxwarp.append([y2, x2])
        yx = yx2
    s += 1
    yx = yxwarp
    
if notgoal:
    print("-1")
else:
    print(s-1)

Submission status: Time Limit Exceeded

Solution code:
import queue

def is_not_road(x, y):
    return x < 0 or x >= h or y < 0 or y >= w or m[x][y] < 0

m = []
q = queue.Queue()

h, w = list(map(int, input().split()))
cx, cy = list(map(lambda c: int(c) - 1, input().split()))
dx, dy = list(map(lambda c: int(c) - 1, input().split()))

for _ in range(h):
    s = input()
    m.append([0 if c == '.' else -1 for c in s])

q.put((cx, cy, 1))

while not q.empty():
    x, y, c = q.get()
    if is_not_road(x, y) or m[x][y] > 0 and m[x][y] <= c:
        continue

    m[x][y] = c

    q.put((x - 1, y, c))
    q.put((x + 1, y, c))
    q.put((x, y - 1, c))
    q.put((x, y + 1, c))

    for i in range(-2, 3):
        for j in range(-2, 3):
            if abs(i) + abs(j) <= 1: continue
            q.put((x + i, y + j, c + 1))

if m[dx][dy] > 0:
    print(m[dx][dy] - 1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import itertools, functools

h, w = map(int, input().split())
ch, cw = tuple(int(s) - 1 for s in input().split())
dh, dw = tuple(int(s) - 1 for s in input().split())
s = [input() for _ in range(h)]

stack = [(ch, cw)]
score = [[float('inf')] * w for _ in range(h)]
score[ch][cw] = 0
while stack:
    x, y = stack.pop()

    for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and score[x][y] < score[nx][ny]:
            score[nx][ny] = score[x][y]
            stack.append((nx, ny))
    
    for dx, dy in itertools.product(range(-2, 3), repeat=2):
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] == '.' and score[x][y] + 1 < score[nx][ny]:
            score[nx][ny] = score[x][y] + 1
            stack.append((nx, ny))

if score[dh][dw] == float('inf'):
    print(-1)
else:
    print(score[dh][dw])

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

S=[]
for i in range(H):
  s=list(input())
  S.append([10**10 if i =="." else -1 for i in s])

dq = deque()
dq.append((Ch,Cw))
S[Ch][Cw]=0

while dq:
  a=dq.pop()
  for i in range(5):
    for j in range(5):
      if a[0]-2+i>=0 and a[0]-2+i<H and a[1]-2+j>=0 and a[1]-2+j<W:
        if abs(i-2)+abs(j-2)==1 and S[a[0]][a[1]]<S[a[0]-2+i][a[1]-2+j]:
          S[a[0]-2+i][a[1]-2+j]=S[a[0]][a[1]]
          dq.appendleft((a[0]-2+i,a[1]-2+j))
        elif S[a[0]][a[1]]+1<S[a[0]-2+i][a[1]-2+j]:
          S[a[0]-2+i][a[1]-2+j]=S[a[0]][a[1]]+1
          dq.append((a[0]-2+i,a[1]-2+j))
      

if S[Dh][Dw]==10**10:
  print(-1)
else:
  print(S[Dh][Dw])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict
from heapq import heappush,heappop,heapify

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ list(sys.stdin.readline().strip()) for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[(1,1),(-1,1),(1,-1),(-1,-1),(2,0),(-2,0),(0,2),(0,-2),(1,2),(-1,2),(1,-2),(-1,-2),(2,1),(-2,1),(2,-1),(-2,-1),(2,2),(-2,2),(2,-2),(-2,-2)]

#隣接リスト
al=defaultdict(lambda: [])

for h in range(H):
    for w in range(W):
        for dh,dw in D:
            if 0<=h+dh<H and 0<=w+dw<W:
                if S[h+dh][w+dw]==".":
                    al[(h,w)].append((0,h+dh,w+dw))    #コスト,toの座標
        for dh,dw in WARP:
            if 0<=h+dh<H and 0<=w+dw<W:
                if S[h+dh][w+dw]==".":
                    al[(h,w)].append((1,h+dh,w+dw))    #コスト,toの座標 ワープはコスト1

d=defaultdict(lambda: float("inf"))    #(h,w):kyori スタート地点からその点までの距離

def dij(x,y):
	d[(x,y)]=0
	hq=[]
	heappush(hq,(0,x,y))
	while hq:
		cost,fro_x,fro_y=heappop(hq)
		for cost,to_x,to_y in al[(fro_x,fro_y)]:
			alt=d[(fro_x,fro_y)]+cost
			if alt<d[(to_x,to_y)]:
				d[(to_x,to_y)]=alt
				heappush(hq, (alt,to_x,to_y))

dij(CH,CW)
if d[(DH,DW)]==float("inf"):
    print -1
else:
    print d[(DH,DW)]

Submission status: Time Limit Exceeded

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

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

visit=defaultdict(lambda: 0) #0:未訪問、1:訪問済み
d=defaultdict(lambda: float("inf")) #スタート地点から各マスまでの距離

q=deque()
q.append((0,CH,CW))
d[(CH,CW)]=0

while q:
    kyori,fro_h, fro_w=q.popleft()
    #print "kyori,fro_h, fro_w, q :: ",kyori, fro_h, fro_w, q
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]<d[(to_h, to_w)] and visit[(to_h, to_w)]==0 :
            visit[(to_h, to_w)]==1
            d[(to_h, to_w)]=d[(fro_h, fro_w)]
            q.appendleft((d[(to_h, to_w)],to_h, to_w))

    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]+1<d[(to_h, to_w)]:
            d[(to_h, to_w)]=d[(fro_h, fro_w)]+1
            q.append((d[(to_h, to_w)],to_h, to_w))

if d[(DH,DW)]==float("inf"):
    print -1
else:
    print d[(DH,DW)]

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

S=[]
for i in range(H):
  s=list(input())
  S.append([10^10 if i =="." else -1 for i in s])

dq = deque()
dq.append((Ch,Cw))
S[Ch][Cw]=0

while dq:
  a=dq.pop()
  for i in range(5):
    for j in range(5):
      if a[0]-2+i>=0 and a[0]-2+i<H and a[1]-2+j>=0 and a[1]-2+j<W and abs(i-2)+abs(j-2)==1:
        S[a[0]-2+i][a[1]-2+j]=min(S[a[0]][a[1]],S[a[0]-2+i][a[1]-2+j])
        dq.appendleft((a[0]-2+i,a[1]-2+j))
      elif a[0]-2+i>=0 and a[0]-2+i<H and a[1]-2+j>=0 and a[1]-2+j<W:
        S[a[0]-2+i][a[1]-2+j]=min(S[a[0]][a[1]]+1,S[a[0]-2+i][a[1]-2+j])
        dq.append((a[0]-2+i,a[1]-2+j))

print(S[Dh][Dw])

Submission status: Time Limit Exceeded

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

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

visit=defaultdict(lambda: 0) #0:未訪問、1:訪問済み
d=defaultdict(lambda: float("inf")) #スタート地点から各マスまでの距離

q=deque()
q.append((CH,CW))
d[(CH,CW)]=0

while q:
    fro_h, fro_w=q.popleft()
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]<d[(to_h, to_w)] and visit[(to_h, to_w)]!=1:
            visit[(to_h, to_w)]==1
            d[(to_h, to_w)]=d[(fro_h, fro_w)]
            q.appendleft((to_h, to_w))

    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]+1<d[(to_h, to_w)] and visit[(to_h, to_w)]!=1:
            visit[(to_h, to_w)]==2
            d[(to_h, to_w)]=d[(fro_h, fro_w)]+1
            q.append((to_h, to_w))

if d[(DH,DW)]==float("inf"):
    print -1
else:
    print d[(DH,DW)]

Submission status: Time Limit Exceeded

Solution code:
#---------------------------------[インポート]---------------------------------#
from collections import deque
#---------------------------------[入力受取・初期設定]---------------------------------#
H, W = map(int, input().split())
C = tuple(map(int, input().split())) # 魔法の位置
D = tuple(map(int, input().split())) # ゴール
D_y = D[0] -1 # 0スタート
D_x = D[1] -1 # 0スタート
S = [list(input()) for _ in range(H)]
visited = [[-1] * W for _ in range(H)]
visited[C[0]-1][C[1]-1] = 0 # 初期値
moves = [(1, 0), (0, 1), (-1, 0), (0, -1)] # 普通の移動
main_q = deque()
magic_q = deque() # マジック用のキュー
main_q.append((C[0]-1, C[1]-1))
#---------------------------------[BFS]---------------------------------#
while main_q:
    y, x = main_q.popleft()
    magic_q.append((y, x))
    for move in moves:
        dy, dx = move
        moved_y = y + dy
        moved_x = x + dx

        if moved_y < 0 or H -1 < moved_y or moved_x < 0 or W -1 < moved_x:
            continue
        if S[moved_y][moved_x] == '#':
            continue
        if S[moved_y][moved_x] == '.' and visited[moved_y][moved_x] == -1:
            main_q.append((moved_y, moved_x))
            visited[moved_y][moved_x] = visited[y][x]
    #---------------------------------[マジック用のBFS]---------------------------------#
    if not main_q: # main_qが空になった場合は探索済みからマジックを使う
        while magic_q:
            y, x = magic_q.popleft()
            for dy in range(-2, 3):
                for dx in range(-2, 3):
                    moved_y = y + dy
                    moved_x = x + dx

                    if moved_y < 0 or H -1 < moved_y or moved_x < 0 or W -1 < moved_x:
                        continue
                    if S[moved_y][moved_x] == '#':
                        continue
                    if S[moved_y][moved_x] == '.' and visited[moved_y][moved_x] == -1:
                        main_q.append((moved_y, moved_x))
                        visited[moved_y][moved_x] = visited[y][x] + 1
#---------------------------------[回答表示]---------------------------------#
answer = visited[D_y][D_x]
print(answer)

Submission status: Time Limit Exceeded

Solution code:
def d_wizard_in_maze():
    from collections import deque
    H, W = [int(i) for i in input().split()]
    Start_row, Start_col = [int(i) - 1 for i in input().split()]
    Goal_row, Goal_col = [int(i) - 1 for i in input().split()]
    Grid = [input() for _ in range(H)]

    neighbor = ((-1, 0), (1, 0), (0, -1), (0, 1))  # 上下左右
    warp = tuple((i, j) for i in range(-2, 3) for j in range(-2, 3)
                 if (i, j) not in neighbor)
    # dist[r][c]: スタートから (r, c) に到達するために必要なワープ回数の最小値
    dist = [[float('inf')] * W for _ in range(H)]

    def is_inside(row, col):
        return 0 <= row < H and 0 <= col < W

    def next_query(row, col, time, _next, cost):
        for dr, dc in _next:
            nr, nc = row + dr, col + dc
            if is_inside(nr, nc) and Grid[nr][nc] == '.' and time < dist[nr][nc]:
                if cost == 0:
                    queue.append((nr, nc, time))
                else:
                    queue.appendleft((nr, nc, time + 1))

    queue = deque([(Start_row, Start_col, 0)])
    while queue:
        row, col, time = queue.pop()
        if time > dist[row][col]:
            continue  # キューに入れた時点では候補だったが、後に歩いて行けるとわかった

        dist[row][col] = time
        if row == Goal_row and col == Goal_col:
            break

        next_query(row, col, time, neighbor, 0)
        next_query(row, col, time, warp, 1)
    return -1 if dist[Goal_row][Goal_col] == float('inf') else dist[Goal_row][Goal_col]

print(d_wizard_in_maze())

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
sy, sx = map(int, input().split())
gy, gx = map(int, input().split())
map_list = []
for i in range(H):
    str_input = input()
    map_list.append(list(str_input))

walk = [[1,0], [-1,0], [0,1], [0,-1]] #　下　上　右　左
warp = [[2,-2], [2,-1], [2,0], [2,1],[2,2], [1,-2], [1,-1], [1,1],[1,2], [0,-2], [0,2], [-1,-2],[-1,-1], [-1,1], [-1,2],[-2,-2], [-2,-1], [-2,0], [-2,1],[-2,2]]

dist = [[10**12 for _ in range(W)] for i in range(H)] #10^3より大きい値

d = deque()
d.append([sy-1, sx-1])
dist[sy-1][sx-1] = 0

#BFS実行部分
while d:
    y,x = d.popleft()
    for dy,dx in walk:
        new_x = x + dx
        new_y = y + dy
        if 0 <= new_y < H and 0 <= new_x < W and map_list[new_y][new_x] == '.' and dist[new_y][new_x] > dist[y][x]:
            dist[new_y][new_x] = dist[y][x]
            d.appendleft([new_y, new_x]) #コスト低い方を優先して取り出すために先頭に追加
    for dy, dx in warp:
        new_x = x + dx
        new_y = y + dy
        if 0 <= new_y < H and 0 <= new_x < W and map_list[new_y][new_x] == '.' and dist[new_y][new_x] > dist[y][x] + 1:
            dist[new_y][new_x] = dist[y][x] + 1
            d.append([new_y, new_x]) #コストが高いので優先順位低い　最高尾に追加

#print(dist)
ans = dist[gy-1][gx-1]
if ans == 10**12:
    ans = -1
print(ans)