Problem:


Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2



Sample input:
4 4
1 1
4 4
..#.
..#.
.#..
.#..


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
import sys
import re
import queue
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    H, W = i_map()
    Ch, Cw = i_map()
    Dh, Dw = i_map()
    Ch,Cw = Ch-1,Cw-1
    Dh,Dw = Dh-1,Dw-1
    maze = [input() for _ in range(H)]

    INF = 10 ** 12
    path = [[INF] * W for _ in range(H)]  # path: 各マスへの移動コスト

    # walk:移動A, warp:移動B
    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]

    q = deque()
    path[Ch][Cw] = 0
    q.append((Ch, Cw, 0))

    while(q):
        ux,uy,s = q.pop()
        for dx,dy in walk:
            nx = ux + dx
            ny = uy + dy
            if(0<=nx<H and 0<=ny<W and maze[nx][ny]=='.' and path[nx][ny] > s):
                path[nx][ny] = s
                q.appendleft((nx,ny,s))
        for dx,dy in warp:
            nx = ux + dx
            ny = uy + dy
            if(0<=nx<H and 0<=ny<W and maze[nx][ny]=='.' and path[nx][ny] > s+1):
                path[nx][ny] = s+1
                q.append((nx,ny,s+1))

    ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
    print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import re
import queue
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    H, W = i_map()
    Ch, Cw = i_map()
    Dh, Dw = i_map()
    Ch,Cw = Ch-1,Cw-1
    Dh,Dw = Dh-1,Dw-1
    maze = [input() for _ in range(H)]

    INF = 10 ** 12
    path = [[INF] * W for _ in range(H)]  # path: 各マスへの移動コスト

    # walk:移動A, warp:移動B
    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]

    q = deque()
    path[Ch][Cw] = 0
    q.append((Ch, Cw, 0))

    while(q):
        ux,uy,s = q.pop()
        for dx,dy in walk:
            nx = ux + dx
            ny = uy + dy
            if(0<=nx<H and 0<=ny<W and maze[nx][ny]=='.' and path[nx][ny] > s):
                path[nx][ny] = s
                q.appendleft((nx,ny,s))
        for dx,dy in warp:
            nx = ux + dx
            ny = uy + dy
            if(0<=nx<H and 0<=ny<W and maze[nx][ny]=='.' and path[nx][ny] > s+1):
                path[nx][ny] = s+1
                q.appendleft((nx,ny,s+1))

    ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
    print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
c = tuple(int(x)+1 for x in input().split())
d = [int(x)+1 for x in input().split()]
maze = [[-1] * (W+4), [-1] * (W+4)]

for i in range(H):
    temp = []
    s0 = input()
    s0 = '11' + s0.replace('.', '0').replace('#', '1') + '11'
    for j, s in enumerate(s0):
        temp.append(-int(s))
    maze.append(temp)
maze.append([-1] * (W+4))
maze.append([-1] * (W+4))

def check55(i, j):
    cset = {(ii, jj) for ii in range(i-2, i+3) for jj in range(j-2, j+3) if maze[ii][jj]==0}
    cset = cset - {(i-1, j), (i, j), (i+1, j), (i, j-1), (i, j+1)}
    return cset

def check(i, j, delta):
    if delta[0] != 0:
        cset = {(i+3*delta[0],jj) for jj in range(j-2, j+3)} 
    else:
        cset = {(ii, j+3*delta[1]) for ii in range(i-2, i+3)}
    return cset

#bfs

k = 1
tempbfs = deque([[c[0], c[1], k]])
flag = 0
while tempbfs:
    if flag == 1:break
    p = tempbfs.popleft()

    #dfs
    if maze[p[0]][p[1]] != 0:continue
    maze[p[0]][p[1]] = p[2]
    if p[0] == d[0] and p[1] == d[1]:
        flag = 1
        k = p[2]
        break
    temp = [(p[0], p[1])]
    dset = set()
    while temp:
        p0 = temp.pop()
        for delta in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            y = p0[0] + delta[0]
            x = p0[1] + delta[1]
            if maze[y][x] != 0: continue
            maze[y][x] = p[2]
            if y == d[0] and x == d[1]:
                flag = 1
                k = p[2]
                break
            temp.append((y, x))
            dset = dset | check(p0[0], p0[1], delta)

    if flag == 1: break
    for l in dset:
        if maze[l[0]][l[1]] == 0:
            tempbfs.append([l[0], l[1], p[2]+1])
    dset = check55(p[0], p[1])
    for l in dset:
        tempbfs.append([l[0], l[1], p[2]+1])

print(k - 1 if flag else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
c = tuple(int(x)+1 for x in input().split())
d = [int(x)+1 for x in input().split()]
maze = [[-1] * (W+4), [-1] * (W+4)]

for i in range(H):
    temp = []
    s0 = input()
    s0 = '11' + s0.replace('.', '0').replace('#', '1') + '11'
    for j, s in enumerate(s0):
        temp.append(-int(s))
    maze.append(temp)
maze.append([-1] * (W+4))
maze.append([-1] * (W+4))

def check55(i, j):
    cset = {(ii, jj) for ii in range(i-2, i+3) for jj in range(j-2, j+3) if maze[ii][jj]==0}
    cset = cset - {(i-1, j), (i, j), (i+1, j), (i, j-1), (i, j+1)}
    return cset

def check(i, j, delta):
    if delta[0] != 0:
        cset = {(i+3*delta[0],jj) for jj in range(j-2, j+3)} 
    else:
        cset = {(ii, j+3*delta[1]) for ii in range(i-2, i+3)}
    return cset

#bfs

k = 1
tempbfs = deque([[c[0], c[1], k]])
flag = 0
while tempbfs:
    if flag == 1:break
    p = tempbfs.popleft()

    #dfs
    if maze[p[0]][p[1]] != 0:continue
    maze[p[0]][p[1]] = p[2]
    if p[0] == d[0] and p[1] == d[1]:
        flag = 1
        k = p[2]
        break
    temp = [(p[0], p[1])]
    dset = set()
    while temp:
        p0 = temp.pop()
        for delta in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            y = p0[0] + delta[0]
            x = p0[1] + delta[1]
            if maze[y][x] != 0: continue
            maze[y][x] = p[2]
            if y == d[0] and x == d[1]:
                flag = 1
                k = p[2]
                break
            temp.append((y, x))
            dset = dset | check(p0[0], p0[1], delta)

    if flag == 1: break
    dset = dset | check55(p[0], p[1])
    for l in dset:
        if maze[l[0]][l[1]] == 0:
            tempbfs.append([l[0], l[1], p[2]+1])

print(k - 1 if flag else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
c = tuple(int(x)+1 for x in input().split())
d = [int(x)+1 for x in input().split()]
maze = [[-1] * (W+4), [-1] * (W+4)]

for i in range(H):
    temp = []
    s0 = input()
    s0 = '11' + s0.replace('.', '0').replace('#', '1') + '11'
    for j, s in enumerate(s0):
        temp.append(-int(s))
    maze.append(temp)
maze.append([-1] * (W+4))
maze.append([-1] * (W+4))

def check55(i, j):
    cset = {(ii, jj) for ii in range(i-2, i+3) for jj in range(j-2, j+3)}
    cset = cset - {(i-1, j), (i, j), (i+1, j), (i, j-1), (i, j+1)}
    return cset

def check(i, j, delta):
    if delta[0] != 0:
        cset = {(i+3*delta[0],jj) for jj in range(j-2, j+3)} 
    else:
        cset = {(ii, j+3*delta[1]) for ii in range(i-2, i+3)}
    return cset

#bfs
dset = set()
k = 1
tempbfs = deque([[c[0], c[1], k]])
flag = 0
while tempbfs:
    if flag == 1:break
    p = tempbfs.popleft()

    #dfs
    if maze[p[0]][p[1]] != 0:continue
    maze[p[0]][p[1]] = p[2]
    if p[0] == d[0] and p[1] == d[1]:
        flag = 1
        k = p[2]
        break
    temp = [(p[0], p[1])]
    dset = check55(p[0], p[1])
    while temp and flag == 0:
        p0 = temp.pop()
        for delta in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            y = p0[0] + delta[0]
            x = p0[1] + delta[1]
            if maze[y][x] != 0: continue
            if y == d[0] and x == d[1]:
                flag = 1
                k = p[2]
                break
            maze[y][x] = p[2]
            temp.append((y, x))
            dset = dset | check(p0[0], p0[1], delta)

    if flag == 1: break
    for l in dset:
        if maze[l[0]][l[1]] == 0:
            tempbfs.append([l[0], l[1], p[2]+1])
    dset = set()
print(k - 1 if flag else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
C0, C1 = map(int, input().split())
D0, D1 = map(int, input().split())

C0 -= 1
C1 -= 1
D0 -= 1
D1 -= 1

map = []
for _ in range(H):
    map.append(input())

inf = 1000000000

q = deque([[C0, C1]])
dist = [[inf for a in range(1100)]for b in range(1100)]
dist[C0][C1] = 0

walk0 = [1, 0, -1, 0]
walk1 = [0, 1, 0, -1]


while q:
    now = q.popleft()
    d = dist[now[0]][now[1]]

    for v in range(4):
        wnxt0 = now[0] + walk0[v]
        wnxt1 = now[1] + walk1[v]

        if wnxt0 < 0 or wnxt0 > H - 1: continue
        elif wnxt1 < 0 or wnxt1 > W - 1: continue
        elif map[wnxt0][wnxt1] == "#": continue
        elif dist[wnxt0][wnxt1] <= d: continue
        
        dist[wnxt0][wnxt1] = d
        q.appendleft([wnxt0, wnxt1])

    for x in [-2, -1, 0, 1, 2]:
        for y in [-2, -1, 0, 1, 2]:
            mnxt0 = now[0] + y
            mnxt1 = now[1] + x

            if mnxt0 < 0 or mnxt0 > H - 1: continue
            elif mnxt1 < 0 or mnxt1 > W - 1: continue
            elif map[mnxt0][mnxt1] == "#": continue
            elif dist[mnxt0][mnxt1] <= d + 1: continue

            dist[mnxt0][mnxt1] = d + 1
            q.append([mnxt0, mnxt1])

ans = dist[D0][D1]

if ans == inf:
    ans = -1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import re
import queue
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def main():
    H, W = i_map()
    Ch, Cw = i_map()
    Dh, Dw = i_map()
    Ch,Cw = Ch-1,Cw-1
    Dh,Dw = Dh-1,Dw-1
    maze = [input() for _ in range(H)]

    INF = 10 ** 12
    path = [[INF] * W for _ in range(H)]  # path: 各マスへの移動コスト

    # walk:移動A, warp:移動B
    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]

    q = deque()
    path[Ch][Cw] = 0
    q.append((Ch, Cw, 0))

    while q:
        x, y, s = q.popleft()
        for dx, dy in walk:  # 移動A
            nx = x + dx
            ny = y + dy
            if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s:
                path[nx][ny] = s
                q.appendleft((nx, ny, s))  # 移動Aの場合はコスト0. キューの先頭に追加する.
        for dx, dy in warp:  # 移動B
            nx = x + dx
            ny = y + dy
            if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s + 1:
                path[nx][ny] = s + 1
                q.append((nx, ny, s + 1))  # 移動Bの場合はコスト1. キューの最後尾に追加する.
    
    ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
    print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    readline = sys.stdin.buffer.readline

    from collections import deque

    h, w = map(int, readline().split())
    c = list(map(int, readline().split()))
    d = list(map(int, readline().split()))
    s = [readline().rstrip().decode('utf-8') for _ in range(h)]

    c = [i-1 for i in c]
    d = [i-1 for i in d]

    t0 = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    t1 = []
    for i in range(-2, 3):
        for j in range(-2, 3):
            t1.append((i, j))
    for i in t0:
        t1.remove(i)
    t1.remove((0, 0))

    check = [[-1]*w for _ in range(h)]
    q = deque()
    q.appendleft((c[0], c[1], 0))

    while q:
        y, x, b = q.pop()
        if x == d[1] and y == d[0]:
            print(b)
            exit()
        if check[y][x] == -1:
            check[y][x] = b
            for dy, dx in t0:
                ydy, xdx = y+dy, x+dx
                if (0 <= xdx < w) and (0 <= ydy < h):
                    if s[ydy][xdx] == '.' and check[ydy][xdx] == -1:
                        q.append((ydy, xdx, b))
            for dy, dx in t1:
                ydy, xdx = y+dy, x+dx
                if (0 <= xdx < w) and (0 <= ydy < h):
                    if s[ydy][xdx] == '.' and check[ydy][xdx] == -1:
                        q.appendleft((ydy, xdx, b+1))
    print(-1)

main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()

from heapq import *

H, W = map(int, input().split())
m1 = lambda s: int(s)-1
sy, sx = map(m1, input().split())
fy, fx = map(m1, input().split())
G = [list(input()) for _ in range(H)]

Q = [(0, sx, sy)]
while Q:
	d, x, y = heappop(Q)
	if G[y][x] == '#': continue
	G[y][x] = '#'

	if (x, y) == (fx, fy):
		print(d)
		break

	for dx in range(-2, 3):
		for dy in range(-2, 3):
			nx = x + dx
			ny = y + dy
			if nx < 0 or ny < 0 or nx >= W or ny >= H or G[ny][nx] == '#': continue
			heappush(Q, (d + (0 if abs(dx) + abs(dy) == 1 else 1), nx, ny))
else:
	print(-1)

Submission status: Time Limit Exceeded

Solution code:
def solve():
    import heapq
    from sys import stdin
    h,w = map(int,input().split())
    si,sj = map(int,input().split())
    gi,gj = map(int,input().split())
    si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
    grid = []
    readline = stdin.readline
    for _ in [0]*h:
        grid.append(readline())
    INF = float("inf")
    dist = [[INF]*w for _ in range(h)]
    dist[si][sj] = 0
    heap = [(0,si,sj)]
    while heap:
        mindist,i,j = heapq.heappop(heap)
        if (i,j) == (gi,gj):
            return mindist
        if mindist > dist[i][j]: continue
        for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
            if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
                if dist[ni][nj] > dist[i][j]:
                    dist[ni][nj] = dist[i][j]
                    heapq.heappush(heap,(dist[ni][nj],ni,nj))
        for ni in range(i-2,i+3):
            if not (0 <= ni and ni < h): continue
            for nj in range(j-2,j+3):
                if not (0 <= nj and nj < w): continue
                if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                    if dist[ni][nj] > dist[i][j] + 1:
                        dist[ni][nj] = dist[i][j] + 1
                        heapq.heappush(heap,(dist[ni][nj],ni,nj))
    return -1
print(solve())

Submission status: Time Limit Exceeded

Solution code:
import heapq
from sys import stdin
h,w = map(int,input().split())
si,sj = map(int,input().split())
gi,gj = map(int,input().split())
si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
grid = []
for _ in [0]*h:
    grid.append(stdin.readline())
INF = float("inf")
dist = [[INF]*w for _ in range(h)]
dist[si][sj] = 0
heap = [(0,si,sj)]
while heap:
    mindist,i,j = heapq.heappop(heap)
    if (i,j) == (gi,gj):
        print(mindist)
        break
    if mindist > dist[i][j]: continue
    for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
        if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
            if dist[ni][nj] > dist[i][j]:
                dist[ni][nj] = dist[i][j]
                heapq.heappush(heap,(dist[ni][nj],ni,nj))
    for ni in range(i-2,i+3):
        if not (0 <= ni and ni < h): continue
        for nj in range(j-2,j+3):
            if not (0 <= nj and nj < w): continue
            if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                if dist[ni][nj] > dist[i][j] + 1:
                    dist[ni][nj] = dist[i][j] + 1
                    heapq.heappush(heap,(dist[ni][nj],ni,nj))
 
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq
from sys import stdin
h,w = map(int,input().split())
si,sj = map(int,input().split())
gi,gj = map(int,input().split())
si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
grid = []
for _ in range(h):
    grid.append(stdin.readline()[:-1])
dist = {(i,j):float("inf") for i in range(h) for j in range(w)}
dist[si,sj] = 0
heap = [(0,si,sj)]
while heap:
    mindist,i,j = heapq.heappop(heap)
    if (i,j) == (gi,gj):
        print(mindist)
        break
    if mindist > dist[i,j]: continue
    for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
        if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
            if dist[ni,nj] > dist[i,j]:
                dist[ni,nj] = dist[i,j]
                heapq.heappush(heap,(dist[ni,nj],ni,nj))
    for ni in range(i-2,i+3):
        if not (0 <= ni and ni < h): continue
        for nj in range(j-2,j+3):
            if not (0 <= nj and nj < w): continue
            if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                if dist[ni,nj] > dist[i,j] + 1:
                    dist[ni,nj] = dist[i,j] + 1
                    heapq.heappush(heap,(dist[ni,nj],ni,nj))
 
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq
h,w = map(int,input().split())
si,sj = map(int,input().split())
gi,gj = map(int,input().split())
si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
grid = []
for _ in range(h):
    grid.append(input())
dist = {(i,j):float("inf") for i in range(h) for j in range(w)}
dist[si,sj] = 0
heap = [(0,si,sj)]
while heap:
    mindist,i,j = heapq.heappop(heap)
    if (i,j) == (gi,gj):
        print(mindist)
        break
    if mindist > dist[i,j]: continue
    for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
        if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
            if dist[ni,nj] > dist[i,j]:
                dist[ni,nj] = dist[i,j]
                heapq.heappush(heap,(dist[ni,nj],ni,nj))
    for ni in range(i-2,i+3):
        if not (0 <= ni and ni < h): continue
        for nj in range(j-2,j+3):
            if not (0 <= nj and nj < w): continue
            if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                if dist[ni,nj] > dist[i,j] + 1:
                    dist[ni,nj] = dist[i,j] + 1
                    heapq.heappush(heap,(dist[ni,nj],ni,nj))
 
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
def solve():
    import collections
    readline = stdin.readline
    h,w = map(int,readline().split())
    si,sj = map(int,readline().split())
    gi,gj = map(int,readline().split())
    si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
    grid = []
    for _ in [0]*h:
        grid.append(readline()[:-1])
    INF = float("inf")
    dist = [[INF]*w for _ in range(h)]
    q = collections.deque([(si,sj)])
    dist[si][sj] = 0
    while q:
        i,j = q.popleft()
        if (i,j) == (gi,gj):
            return dist[i][j]
        for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
            if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
                if dist[ni][nj] > dist[i][j]:
                    dist[ni][nj] = dist[i][j]
                    q.appendleft((ni,nj))
        listj = range(j-2,j+3)
        for ni in range(i-2,i+3):
            if not (0 <= ni and ni < h): continue
            for nj in listj:
                if not (0 <= nj and nj < w): continue
                if grid[ni][nj] == "." and dist[ni][nj] > dist[i][j] + 1:
                    dist[ni][nj] = dist[i][j] + 1
                    q.append((ni,nj))

    return -1

print(solve())

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
def solve():
    import collections
    readline = stdin.readline
    h,w = map(int,readline().split())
    si,sj = map(int,readline().split())
    gi,gj = map(int,readline().split())
    si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
    grid = []
    for _ in [0]*h:
        grid.append(readline()[:-1])
    INF = float("inf")
    dist = [[INF]*w for _ in range(h)]
    q = collections.deque([(si,sj)])
    dist[si][sj] = 0
    while q:
        i,j = q.popleft()
        if (i,j) == (gi,gj):
            return dist[i][j]
        for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
            if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
                if dist[ni][nj] > dist[i][j]:
                    dist[ni][nj] = dist[i][j]
                    q.appendleft((ni,nj))
        listj = range(j-2,j+3)
        for ni in range(i-2,i+3):
            if not (0 <= ni and ni < h): continue
            for nj in listj:
                if not (0 <= nj and nj < w): continue
                if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                    if dist[ni][nj] > dist[i][j] + 1:
                        dist[ni][nj] = dist[i][j] + 1
                        q.append((ni,nj))

    return -1

print(solve())

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
def solve():
    import collections
    readline = stdin.readline
    h,w = map(int,readline().split())
    si,sj = map(int,readline().split())
    gi,gj = map(int,readline().split())
    si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
    grid = []
    for _ in range(h):
        grid.append(readline()[:-1])
    INF = float("inf")
    dist = {(i,j):INF for i in range(h) for j in range(w)}
    q = collections.deque([(si,sj)])
    dist[si,sj] = 0
    while q:
        i,j = q.popleft()
        if (i,j) == (gi,gj):
            return dist[i,j]
        for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
            if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
                if dist[ni,nj] > dist[i,j]:
                    dist[ni,nj] = dist[i,j]
                    q.appendleft((ni,nj))
        for ni in range(i-2,i+3):
            if not (0 <= ni and ni < h): continue
            for nj in range(j-2,j+3):
                if not (0 <= nj and nj < w): continue
                if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                    if dist[ni,nj] > dist[i,j] + 1:
                        dist[ni,nj] = dist[i,j] + 1
                        q.append((ni,nj))

    return -1

print(solve())

Submission status: Time Limit Exceeded

Solution code:
import collections
h,w = map(int,input().split())
si,sj = map(int,input().split())
gi,gj = map(int,input().split())
si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
grid = []
for _ in range(h):
    grid.append(input())
dist = {(i,j):float("inf") for i in range(h) for j in range(w)}
q = collections.deque([(si,sj)])
dist[si,sj] = 0
while q:
    i,j = q.popleft()
    if (i,j) == (gi,gj):
        print(dist[i,j])
        break
    for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
        if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
            if dist[ni,nj] > dist[i,j]:
                dist[ni,nj] = dist[i,j]
                q.appendleft((ni,nj))
    for ni in range(i-2,i+3):
        if not (0 <= ni and ni < h): continue
        for nj in range(j-2,j+3):
            if not (0 <= nj and nj < w): continue
            if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                if dist[ni,nj] > dist[i,j] + 1:
                    dist[ni,nj] = dist[i,j] + 1
                    q.append((ni,nj))

else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq
h,w = map(int,input().split())
si,sj = map(int,input().split())
gi,gj = map(int,input().split())
si,sj,gi,gj = si-1,sj-1,gi-1,gj-1
grid = []
for _ in range(h):
    grid.append(input())
dist = {(i,j):float("inf") for i in range(h) for j in range(w)}
dist[si,sj] = 0
heap = [(0,si,sj)]
while heap:
    mindist,i,j = heapq.heappop(heap)
    if (i,j) == (gi,gj):
        print(mindist)
        break
    if mindist > dist[i,j]: continue
    for ni,nj in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
        if 0 <= ni and ni < h and 0 <= nj and nj < w and grid[ni][nj] == ".":
            if dist[ni,nj] > dist[i,j]:
                dist[ni,nj] = dist[i,j]
                heapq.heappush(heap,(dist[ni,nj],ni,nj))
    for ni in range(i-2,i+3):
        if not (0 <= ni and ni < h): continue
        for nj in range(j-2,j+3):
            if not (0 <= nj and nj < w): continue
            if (ni,nj) not in [(i,j),(i+1,j),(i-1,j),(i,j+1),(i,j-1)] and grid[ni][nj] == ".":
                if dist[ni,nj] > dist[i,j] + 1:
                    dist[ni,nj] = dist[i,j] + 1
                    heapq.heappush(heap,(dist[ni,nj],ni,nj))

else:
    print(-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)]

INF = 10 ** 12
path = [[INF] * W for _ in range(H)]  # path: 各マスへの移動コスト

# walk:移動A, warp:移動B
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]

q = deque()
path[Ch][Cw] = 0
q.append((Ch, Cw, 0))

while q:
    x, y, s = q.popleft()
    for dx, dy in walk:  # 移動A
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s:
            path[nx][ny] = s
            q.append((nx, ny, s))  # 移動Aの場合はコスト0. キューの先頭に追加する.
    for dx, dy in warp:  # 移動B
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s + 1:
            path[nx][ny] = s + 1
            q.append((nx, ny, s + 1))  # 移動Bの場合はコスト1. キューの最後尾に追加する.
    
ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

H, W, ch, cw, gh, gw, *S = open(0).read().split()
H, W, ch, cw, gh, gw = [int(_) - 1 for _ in [H, W, ch, cw, gh, gw]]
S = ''.join(S)
H += 1
W += 1

X = []
Y = []
D = []
for i in range(H * W):
    if S[i] == '#':
        continue
    h, w = divmod(i, W)
    for dh in range(-2, 3):
        for dw in range(-2, 3):
            j = i + dw + W * dh
            if 0 <= h + dh < H and 0 <= w + dw < W and i < j and S[j] == '.':
                X += [i]
                Y += [j]
                D += [0 if (dh, dw) in ((1, 0), (0, 1)) else 1]
dist = dijkstra(
    csr_matrix((D, (X, Y)), (H * W, H * W), dtype=int),
    indices=ch * W + cw,
    directed=0)
ans = dist[gh * W + gw]
if ans > 10**10:
    ans = -1
else:
    ans = int(ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix

H, W, ch, cw, gh, gw, *S = open(0).read().split()
H, W, ch, cw, gh, gw = [int(_) - 1 for _ in [H, W, ch, cw, gh, gw]]
H += 1
W += 1

X = []
Y = []
D = []
for i in range(H * W):
    h, w = divmod(i, W)
    if S[h][w] == '#':
        continue
    for dh in range(-2, 3):
        for dw in range(-2, 3):
            if 0 <= h + dh < H and 0 <= w + dw < W and (
                    dh > 0 or
                (dh == 0 and dw > 0)) and S[h + dh][w + dw] == '.':
                X += [i]
                Y += [i + dw + W * dh]
                D += [0 if (dh, dw) in ((1, 0), (0, 1)) else 1]
dist = dijkstra(
    csr_matrix((D, (X, Y)), (H * W, H * W), dtype=int),
    indices=ch * W + cw,
    directed=0)
ans = dist[gh * W + gw]
if ans > 10**10:
    ans = -1
else:
    ans = int(ans)
print(ans)