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:
#! /usr/bin/env python3
from collections import defaultdict
import heapq
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF=10**20
def main():
    H,W=mi()
    Ch,Cw=mi()
    Dh,Dw=mi()

    Ch-=1
    Cw-=1
    Dh-=1
    Dw-=1

    G = []
    for i in range(H):
        S=list(input())
        G.append(S)

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

    mx = H*W
    edge = defaultdict(lambda: [])

    for h in range(H):
        for w in range(W):
            if G[h][w] == "#": continue
            normal = set([(h-1,w),(h+1,w),(h,w+1),(h,w-1)])
            for dh in range(-2,3):
                for dw in range(-2,3):
                    new_h,new_w = h+dh,w+dw
                    cost = 1

                    if dh == 0 and dw == 0: continue
                    if not (0<=new_h<H and 0<=new_w<W): continue
                    if G[new_h][new_w] == "#":  continue
                    if (new_h,new_w) in normal:
                        cost -= 1
                    
                    edge[(h,w)].append(((new_h,new_w),cost))
                    # edge[y].append((x,cost))
    

    s = (Ch,Cw)
    t = (Dh,Dw)

    hq = []
    heapq.heappush(hq,(0,s))

    dist = defaultdict(lambda: INF) # sからxでの最短距離
    dist[s] = 0
    while hq: 
        d,x = heapq.heappop(hq) # sからxまでの最短経路を探索する
        if dist[x] < d: continue

        for e,cost in edge[x]:
            if dist[e] > dist[x] + cost:
                dist[e] = dist[x] + cost
                heapq.heappush(hq,(dist[e],e))
        
    # print(dist)
    if dist[t] == INF: 
        dist[t] = -1
        
    print(dist[t])


if __name__ == "__main__":
    main()

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, cw, dh, dw = ch-1, cw-1, dh-1, dw-1
s = [input() for _ in range(H)]

d = [[-1]*W for _ in range(H)]

que = deque([[cw, ch, 0]])
while que:
    x, y, cost = que.popleft()
    if d[y][x]==-1 or d[y][x]>cost:
        d[y][x] = cost
        for dx in range(-2, 3):
            for dy in range(-2, 3):
                nx, ny = x+dx, y+dy
                if 0<=nx<W and 0<=ny<H and s[ny][nx]!='#':
                    if abs(dx)+abs(dy) == 1:
                        que.append([nx, ny, cost])
                    else:
                        que.append([nx, ny, cost+1])  
print(d[dh][dw])

Submission status: Time Limit Exceeded

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]
dst[sh][sw] = 0

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if -1 < dst[nh][nw] <= d: continue
        dst[nh][nw] = d
        dq.appendleft((nh, nw, d))

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if -1 < dst[nh][nw] <= d: continue
        dst[nh][nw] = d + 1
        dq.appendleft((nh, nw, d + 1))

print(dst[eh][ew])

Submission status: Time Limit Exceeded

Solution code:
#! /usr/bin/env python3
from collections import defaultdict
import heapq
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF=10**20
def main():
    H,W=mi()
    Ch,Cw=mi()
    Dh,Dw=mi()

    Ch-=1
    Cw-=1
    Dh-=1
    Dw-=1

    G = []
    for i in range(H):
        S=list(input())
        G.append(S)

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

    mx = H*W
    edge = defaultdict(lambda: [])

    for h in range(H):
        for w in range(W):
            if G[h][w] == "#": continue
            normal = [(h-1,w),(h+1,w),(h,w+1),(h,w-1)]
            for dh in range(-2,3):
                for dw in range(-2,3):
                    new_h,new_w = h+dh,w+dw
                    cost = 1

                    if dh == 0 and dw == 0: continue
                    if not (0<=new_h<H and 0<=new_w<W): continue
                    if G[new_h][new_w] == "#":  continue
                    if (new_h,new_w) in normal:
                        cost -= 1
                    
                    edge[(h,w)].append(((new_h,new_w),cost))
                    # edge[y].append((x,cost))
    

    s = (Ch,Cw)
    t = (Dh,Dw)

    hq = []
    heapq.heappush(hq,(0,s))

    dist = defaultdict(lambda: INF) # sからxでの最短距離
    dist[s] = 0
    while hq: 
        d,x = heapq.heappop(hq) # sからxまでの最短経路を探索する
        if dist[x] < d: continue

        for e,cost in edge[x]:
            if dist[e] > dist[x] + cost:
                dist[e] = dist[x] + cost
                heapq.heappush(hq,(dist[e],e))
        
    # print(dist)
    if dist[t] == INF: 
        dist[t] = -1
        
    print(dist[t])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]
dst[sh][sw] = 0

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if -1 < dst[nh][nw] <= d: continue
        dst[nh][nw] = d
        dq.appendleft((nh, nw, d))

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if -1 < dst[nh][nw] <= d + 1: continue
        dst[nh][nw] = d + 1
        dq.appendleft((nh, nw, d + 1))

print(dst[eh][ew])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

h, w = map(int, input().split())
ci, cj = map(lambda x: int(x) - 1, input().split())
di, dj = map(lambda x: int(x) - 1, input().split())
mapp = []
for _ in range(h):
    mapp.append(list(input()))

walk_ways = [(-1, 0), (1, 0), (0, 1), (0, -1)]
warp_ways = [(i, j) for i in range(-2, 3) for j in range(-2, 3)]

d = deque()
cost = 0
while 1:
    while 1:
        for way in walk_ways:
            if ci + way[0] >= h or ci + way[0] < 0:
                continue
            elif cj + way[1] >= w or cj + way[1] < 0:
                continue
            elif mapp[ci + way[0]][cj + way[1]] == '#':
                continue
            elif type(mapp[ci + way[0]][cj + way[1]]) == int:
                continue
            else:
                d.appendleft((ci + way[0], cj + way[1]))
                mapp[ci + way[0]][cj + way[1]] = cost
        if not d:
            break
        ci, cj = d[0][0], d[0][1]
        d.popleft()

    for way in warp_ways:
        if ci + way[0] >= h or ci + way[0] < 0:
            continue
        elif cj + way[1] >= w or cj + way[1] < 0:
            continue
        elif mapp[ci + way[0]][cj + way[1]] == '#':
            continue
        elif type(mapp[ci + way[0]][cj + way[1]]) == int:
            continue
        else:
            d.append((ci + way[0], cj + way[1]))
    continue
    if not d:
        break

    ci, cj = d[0][0], d[0][1]
    d.popleft()
    cost += 1
    mapp[ci][cj] = cost
if mapp[di][dj] == '.':
    print(-1)
else:
    print(mapp[di][dj])

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 = []
for _ in range(H):
    S.append(list(input()))

warp = [[-1 for i in range(W)]for j in range(H)]

Q = deque([[Ch-1,Cw-1,0]])

while(len(Q) != 0):
    x,y,cnt = Q.popleft()

    if(warp[x][y] != -1):   #skip
        continue

    warp[x][y] = cnt        #ワープ魔法の必要回数

    for tx in range(-2,3):
        for ty in range(-2,3):
            nx = x+tx
            ny = y+ty

            if(0 <= nx < H and 0<= ny < W and S[nx][ny]=="."):
                if(abs(tx)+abs(ty) == 1):#徒歩で行けるなら前に
                    Q.appendleft([nx,ny,cnt])
                elif(abs(tx)+abs(ty)>=2):#ワープ魔法必要なら後ろに
                    Q.append([nx,ny,cnt+1])

print(warp[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())
maze = [input() for _ in range(H)]

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]

INF = 10 ** 12
cost = [[INF] * W for _ in range(H)]
q = deque()
cost[CH][CW] = 0
q.append((CH, CW, 0))

while q:
	x, y, s = q.popleft()
	for dx, dy in WALK:
		nx, ny = x + dx, y + dy
		if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and cost[nx][ny] > s:
			cost[nx][ny] = s
			q.appendleft((nx, ny, s))
	for dx, dy in WARP:
		nx, ny = x + dx, y + dy
		if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and cost[nx][ny] > s + 1:
			cost[nx][ny] = s + 1
			q.append((nx, ny, s + 1))
ans = cost[DH][DW] if cost[DH][DW] < INF else '-1'
print(ans)

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())
maze = [input() for _ in range(H)]

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]

INF = 10 ** 12
cost = [[INF] * W for _ in range(H)]
q = deque()
cost[CH][CW] = 0
q.append((CH, CW, 0))

while q:
	x, y, s = q.popleft()
	for dx, dy in WALK:
		nx, ny = x + dx, y + dy
		if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and cost[nx][ny] > s:
			cost[nx][ny] = s
			q.appendleft((nx, ny, s))
	for dx, dy in WARP:
		nx, ny = x + dx, y + dy
		if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and cost[nx][ny] > s + 1:
			cost[nx][ny] = s + 1
			q.appendleft((nx, ny, s + 1))
ans = cost[DH][DW] if cost[DH][DW] < INF else '-1'
print(ans)

Submission status: Time Limit Exceeded

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] == -1 or d < dst[nh][nw]:
            dq.appendleft((nh, nw, d))
            dst[nh][nw] = d

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        if dst[nh][nw] == -1 or d + 1 < dst[nh][nw]:
            dq.append((nh, nw, d + 1))
            dst[nh][nw] = d + 1

print(dst[eh][ew])

Submission status: Time Limit Exceeded

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()
    # if h == eh and w == ew:
    #     dst[h][w] = d
    #     break

    # if dst[h][w] >= 0 or S[h][w] == '#': continue
    # if dst[h][w] >= 0: continue
    # if dst[h][w] == -1 or d < dst[h][w]: dst[h][w] = d
    # else: continue
    # dst[h][w] = d

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        # if dst[nh][nw] >= 0: continue
        if dst[nh][nw] == -1 or d < dst[nh][nw]:
            dq.appendleft((nh, nw, d))
            dst[nh][nw] = d

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        if dst[nh][nw] == -1 or d + 1 < dst[nh][nw]:
            dq.append((nh, nw, d + 1))
            dst[nh][nw] = d + 1

print(dst[eh][ew])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
CH, CW = tuple(int(x) - 1 for x in input().split())
DH, DW = tuple(int(x) - 1 for x in input().split())
maze = [input() for _ in range(H)]

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]

INF = 10 ** 12
cost = [[INF] * W for _ in range(H)]
q = deque()
cost[CH][CW] = 0
q.append((CH, CW, 0))

while q:
	x, y, s = q.popleft()
	for dx, dy in WALK:
		nx, ny = x + dx, y + dy
		if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and cost[nx][ny] > s:
			cost[nx][ny] = s
			q.appendleft((nx, ny, s))
	for dx, dy in WARP:
		nx, ny = x + dx, y + dy
		if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and cost[nx][ny] > s + 1:
			cost[nx][ny] = s + 1
			q.appendleft((nx, ny, s + 1))
ans = cost[DH][DW] if cost[DH][DW] < INF else '-1'
print(ans)

Submission status: Time Limit Exceeded

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()
    if h == eh and w == ew:
        dst[h][w] = d
        break

    if dst[h][w] >= 0 or S[h][w] == '#': continue
    if dst[h][w] == -1 or d < dst[h][w]: dst[h][w] = d

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        dq.appendleft((nh, nw, d))

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        dq.append((nh, nw, d+1))

print(dst[eh][ew])

Submission status: Time Limit Exceeded

Solution code:
import math
from itertools import product
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 _ in range(h)]


distance = [[math.inf for _ in range(w)] for _ in range(h)]
distance[ch][cw] = 0
queue = deque([(ch, cw)])
pathes = {(0, -1), (-1, 0), (0, 1), (1, 0)}
warps = set(product(range(-2, 3), range(-2, 3))) - {(0, 0)} - pathes

while queue:
    i, j = queue.popleft()
    for pi, pj in pathes:
        u, v = i+pi, j+pj
        if 0 <= u < h and 0 <= v < w and S[u][v] == '.' and distance[u][v] > distance[i][j]:
            distance[u][v] = distance[i][j]
            queue.appendleft((u, v))

    for wi, wj in warps:
        x, y = i + wi, j + wj
        if 0 <= x < h and 0 <= y < w and S[x][y] == '.' and distance[x][y] > distance[i][j] + 1:
            distance[x][y] = distance[i][j] + 1
            queue.append((x, y))

print(distance[dh][dw] if distance[dh][dw] != math.inf else -1)

Submission status: Time Limit Exceeded

Solution code:
import math
from itertools import product
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 _ in range(h)]


distance = [[math.inf for _ in range(w)] for _ in range(h)]
distance[ch][cw] = 0
queue = deque([(ch, cw)])

while queue:
    i, j = queue.popleft()
    adj = []
    if i > 0 and S[i - 1][j] == '.':
        adj.append((i-1, j))
    if j > 0 and S[i][j - 1] == '.':
        adj.append((i, j - 1))
    if i < h-1 and S[i + 1][j] == '.':
        adj.append((i+1, j))
    if j < w-1 and S[i][j+1] == '.':
        adj.append((i, j+1))
    for u, v in adj:
        if distance[u][v] > distance[i][j]:
            distance[u][v] = distance[i][j]
            queue.appendleft((u,v))

    warp = product(range(max(i-2, 0), min(i+3, h)),
                   range(max(j-2, 0), min(j+3, w)))
    for x, y in warp:
        if (x,y) != (i,j) and (x,y) not in adj and S[x][y] == '.' and distance[x][y] > distance[i][j] + 1:
            distance[x][y] = distance[i][j] + 1
            queue.append((x,y))

print(distance[dh][dw] if distance[dh][dw] != math.inf else -1)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

from collections import deque

q = 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

# mylist = [[]]
ban_list = [[-1 for j in range(w)] for i in range(h)]
cost_list = [[-1 for j in range(w)] for i in range(h)]

# print(mylist)

for i in range(h):
  # 文字列の入力
  s = input()
  for j in range(len(s)):
    ban_list[i][j] = s[j]

ban_list[ch][cw] = 0
# cost_list[ch][cw] = 0

cost = 0
ph = ch
pw = cw

q.append([ph, pw])


# # 最後デバッグ
# for li in ban_list:
#   print(li)



loop = True
while loop:
  # print(len(q))
  ph, pw = q.popleft()
  cost = ban_list[ph][pw]

  # print(ph, pw)
  # print(cost)
  # 上
  if ph == 0:
    pass
  else:
    if ban_list[ph-1][pw] != "#" and ban_list[ph-1][pw] != cost:
      if ban_list[ph-1][pw] == "." or cost < ban_list[ph-1][pw]:
        ban_list[ph-1][pw] = cost
        q.appendleft([ph-1, pw])
    else:
      pass

  # 右
  if pw == w -1:
    pass
  else:
    if ban_list[ph][pw + 1] != "#" and ban_list[ph][pw + 1] != cost:
      if ban_list[ph][pw + 1] == "." or cost < ban_list[ph][pw + 1]:
        ban_list[ph][pw + 1] = cost
        q.appendleft([ph, pw+1])
    else:
      pass

  # 下
  if ph == h -1:
    pass
  else:
    if ban_list[ph+1][pw] != "#" and ban_list[ph+1][pw] != cost:
      if ban_list[ph+1][pw] == "." or cost < ban_list[ph+1][pw]:
        ban_list[ph+1][pw] = cost
        q.appendleft([ph+1, pw])
    else:
      pass

  # 左
  if pw == 0:
    pass
  else:
    if ban_list[ph][pw - 1] != "#" and ban_list[ph][pw - 1] != cost:
      if ban_list[ph][pw - 1] == "." or cost < ban_list[ph][pw - 1]:
        ban_list[ph][pw - 1] = cost
        q.appendleft([ph, pw-1])
    else:
      pass


  # ジャンプ--------------
  for i in range(-2, 3):
    if (ph + i < 0) or (h - 1 < ph + i):
      continue

    for j in range(-2, 3):
      if (pw + j < 0) or (w - 1 < pw + j) or (i==0 and j == 0) or (i==0 and j == -1) or (i==0 and j == 1) or (i==-1 and j == 0) or (i==1 and j == 0):
        continue
      if ban_list[ph + i][pw + j] == ".":
        # print(ph, pw)
        # print(i, j)
        # print(cost)
        ban_list[ph + i][pw + j] = cost + 1
        q.append([ph + i, pw + j])

  if len(q) == 0:
    loop = False


result = ban_list[dh][dw]
if result == ".":
  result = -1

# # 最後デバッグ
# for li in ban_list:
#   print(li)

print(result)

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
C=(Ch,Cw)
D=(Dh,Dw)
S=[list(input()) for i in range(H)]
dist=[[10**15 for j in range(W)] for i in range(H)]
dist[Ch][Cw]=0
q=deque([C])
dx=[1,0,-1,0]
dy=[0,1,0,-1]
while(len(q)>0):
    x,y=q.popleft()
    for k in range(4):
        nx=x+dx[k]
        ny=y+dy[k]
        if 0<=nx<H and 0<=ny<W:
            if S[nx][ny]=="#":
                continue
            if dist[nx][ny]>dist[x][y]:
                dist[nx][ny]=dist[x][y]
                q.appendleft((nx,ny))
    for i in range(-2,3):
        for j in range(-2,3):
            nx=x+i
            ny=y+j
            if 0<=nx<H and 0<=ny<W:
                if S[nx][ny]=="#":
                    continue
                if dist[nx][ny]>dist[x][y]+1:
                    dist[nx][ny]=dist[x][y]+1
                    q.append((nx,ny))
if dist[Dh][Dw]==10**15:
    print(-1)
else:
    print(dist[Dh][Dw])

Submission status: Time Limit Exceeded

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()

    if dst[h][w] == -1: dst[h][w] = d
    else: dst[h][w] = min(dst[h][w], d)

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        dq.appendleft((nh, nw, d))

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        dq.append((nh, nw, d+1))

print(dst[eh][ew])

Submission status: Time Limit Exceeded

Solution code:
import math
from itertools import product
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 _ in range(h)]

reached = [[False for _ in range(w)] for _ in range(h)]
distance = [[math.inf for _ in range(w)] for _ in range(h)]
distance[ch][cw] = 0
queue = deque([(ch, cw)])

while queue:
    i, j = queue.popleft()
    reached[i][j] = True
    adj = []
    if i > 0 and S[i - 1][j] == '.':
        adj.append((i-1, j))
    if j > 0 and S[i][j - 1] == '.':
        adj.append((i, j - 1))
    if i < h-1 and S[i + 1][j] == '.':
        adj.append((i+1, j))
    if j < w-1 and S[i][j+1] == '.':
        adj.append((i, j+1))
    for u, v in adj:
        if not reached[u][v]:
            distance[u][v] = min(distance[i][j],  distance[u][v])
            queue.appendleft((u,v))

    warp = product(range(max(i-2, 0), min(i+3, h)),
                   range(max(j-2, 0), min(j+3, w)))
    for x, y in warp:
        if (x,y) != (i,j) and (x,y) not in adj and S[x][y] == '.' and not reached[x][y]:
            distance[x][y] = min(distance[i][j] + 1,  distance[x][y])
            queue.append((x,y))

print(distance[dh][dw] if distance[dh][dw] != math.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())
maze = [[9]*(w+4)]
maze.append([9]*(w+4))
for i in range(h):
  s = input()
  tmp = [9,9]
  for i in s:
    if i == "#":
      tmp.append(9)
    else:
      tmp.append(0)
  tmp.append(9)
  tmp.append(9)
  maze.append(tmp)
maze.append([9]*(w+4))
maze.append([9]*(w+4))
#print(maze)

pos = deque()
pos.append([ch+1,cw+1,0])
while len(pos)>0:
  x, y, hop = pos.popleft()
  #print(pos)
  #print[x,y,hop)
  if (x,y) == (dh+1,dw+1):
    print(hop)
    break
  maze[x][y] = 3
  
  if maze[x-1][y] <3:
    pos.appendleft([x-1,y,hop])
    maze[x-1][y] = 3  
    
  if maze[x+1][y] <3:
    pos.appendleft([x+1,y,hop])
    maze[x+1][y] = 3
    
  if maze[x][y-1] <3:
    pos.appendleft([x,y-1,hop])
    maze[x][y-1] = 3
    
  if maze[x][y+1] <3:
    pos.appendleft([x,y+1,hop])
    maze[x][y+1] = 3

  move =[(-2,0),(-2,1),(-2,2),(-2,-1),(-2,-2),(2,0),(2,1),(2,2),(2,-1),(2,-2),(0,-2),(-1,-2),(1,-2),(0,2),(-1,2),(1,2),(-1,1),(-1,-1),(1,1),(1,-1)]
  for dx,dy in move:
    if maze[x+dx][y+dy] <2:
      pos.append([x+dx,y+dy,hop+1])
      maze[x+dx][y+dy] = 2
  
else:
  print(-1)