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
from itertools import product
h, w = map(int, input().split())
si, sj = map(lambda x: int(x)-1, input().split())
gi, gj = map(lambda x: int(x)-1, input().split())
fld = ''.join([input()for _ in range(h)])
INF = 10**18


def to_v(i, j):
    return i*w+j


n = h*w
start = to_v(si, sj)
goal = to_v(gi, gj)


def generate_v2(v):
    i, j = divmod(v, w)
    if 0 < i:
        yield v-w
    if i < h-1:
        yield v+w
    if 0 < j:
        yield v-1
    if j < w-1:
        yield v+1


def generate_v2_b(v):
    i, j = divmod(v, w)
    it = [-2, -1, 0, 1, 2]
    for di, dj in product(it, repeat=2):
        x, y = i+di, j+dj
        if x < 0 or h <= x or y < 0 or w <= y:
            continue
        yield x*w+y


def bfs(init_v):
    next_v = deque([init_v])
    dist = [INF]*n
    dist[init_v] = 0
    while next_v:
        v = next_v.popleft()
        for v2 in generate_v2(v):
            if fld[v2] == '#':
                continue
            if dist[v2] <= dist[v]:
                continue
            dist[v2] = dist[v]
            next_v.append(v2)

        for v2 in generate_v2_b(v):
            if fld[v2] == '#':
                continue
            if dist[v2] <= dist[v]+1:
                continue
            dist[v2] = dist[v]+1
            next_v.append(v2)

    return dist


ans = bfs(start)[goal]
print(-1 if ans == INF else ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


def solve():
    readline = sys.stdin.readline
    H, W = map(int, readline().split())
    ch, cw = map(int, readline().split())
    dh, dw = map(int, readline().split())
    S = ['#' * (W+2)]
    for _ in range(H):
        S.append('#' + readline() + '#')
    S.append('#' * (W+2))
    H += 2
    W += 2
    start = ch*W + cw
    goal = dh*W + dw
    q = deque([start])
    inf = 999_999_999
    dist = [inf] * (H*W)
    dist[start] = 0
    D1 = [-W, -1, 1, W]
    D2 = []
    for dy in [-2*W, -W, 0, W, 2*W]:
        for dx in range(-2, 3):
            D2.append(dy+dx)

    while q:
        x = q.popleft()
        for d in D1:
            i, j = divmod(x+d, W)
            if S[i][j] == '.' and dist[x+d] > dist[x]:
                q.appendleft(x+d)
                dist[x+d] = dist[x]
    
        for d in D2:
            xx = x + d
            i, j = divmod(xx, W)
            if 0 <= xx < W*H and dist[xx] > dist[x] and S[i][j] == '.':
                q.append(xx)
                dist[xx] = dist[x] + 1
    return dist[goal] if dist[goal] != inf else -1


if __name__ == '__main__':
    ans = solve()
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())  # 縦H X 横W マス
C = list(map(int, input().split()))  #[Ch, Cw]　　*1多いことに注意
D = list(map(int, input().split()))  #[Dh, Dw]　　*1多いことに注意
S = [list(input()) for _ in range(H)]  #Sij = S[i][j]  

T = deque([[C[0]-1,C[1]-1]])
ans = 0

move = [[-1,0],[1,0],[0,-1],[0,1]]
magic = [[-2,-2],[-2,-1],[-2,0],[-2,1],[-2,2],[-1,-2],[-1,-1],[-1,0],[-1,1],[-1,2],\
         [0,-2],[0,-1],[0,0],[0,1],[0,2],[1,-2],[1,-1],[1,0],[1,1],[1,2],[2,-2],[2,-1],\
         [2,0],[2,1],[2,2]]

# 繰り返し
while T:
    K = deque([])
    while T:
        y,x = T.popleft()
        if 0 <= y < H and 0 <= x < W and S[y][x] =="." :
            K.append([y,x])
            S[y][x] = "#"
            for i,j in move:
                T.append([y+i,x+j])
    if [D[0]-1,D[1]-1] in K:
        print(ans)
        break
    ans += 1
    for z,w in K:
        for s_y, s_x in magic:
                if 0 <= z+s_y < H and 0 <= w+s_x < W and S[z+s_y][w+s_x] ==".":
                    if not S[z+s_y][w+s_x] in K and not [z+s_y,w+s_x] in T:
                        T.append([z+s_y, w+s_x])
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import heapq
import sys
input=sys.stdin.readline

def calc():
  h,w=map(int,input().split())
  sy,sx=map(int,input().split())
  gy,gx=map(int,input().split())
  board=[['#']*(w+2)]+[list('#'+input().replace('\n','')+'#') for _ in range(h)]+[['#']*(w+2)]
  costs=[[10**18]*(w+1) for _ in range(h+1)]
  costs[sy][sx]=0
  q=[]
  heapq.heappush(q,(0,sy,sx))
  while len(q)!=0:
    cost,y,x=heapq.heappop(q)
    if y==gy and x==gx:
      print(cost)
      exit()
    for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
      if 1<=y+dy<=h and 1<=x+dx<=w and board[y+dy][x+dx]=='.' and costs[y+dy][x+dx]>costs[y][x]:
        costs[y+dy][x+dx]=costs[y][x]
        heapq.heappush(q,(cost,y+dy,x+dx))
    for dy in range(-2,3):
      for dx in range(-2,3):
        if dy==0 and dx==0:
          continue
        if 1<=y+dy<=h and 1<=x+dx<=w and board[y+dy][x+dx]=='.' and costs[y+dy][x+dx]>costs[y][x]+1:
          costs[y+dy][x+dx]=costs[y][x]+1
          heapq.heappush(q,(cost+1,y+dy,x+dx))
  print(-1)
calc()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h, w = map(int, input().split())
cy, cx = map(lambda x: int(x) - 1, input().split())
dy, dx = map(lambda x: int(x) - 1, input().split())
table = [list(input()) for _ in range(h)]
if cy == dy and cx == dx:
    print(0)
    exit()
if table[cy][cx] == "#" or table[dy][dx] == "#":
    print(-1)
    exit()
stack = deque()
stack.append([cy, cx])
table[cy][cx] = 0
step = [0, 1, 0, -1, 0]
step2 = [[-2, -2], [-2, -1], [-2, 0], [-2, 1], [-2, 2], [-1, -2], [-1, 2],
         [0, -2], [0, 2], [1, -2], [1, 2], [2, -2], [2, -1], [2, 0], [2, 1],
         [2, 2], [-1, -1], [-1, 1], [1, -1], [1, 1]]
while len(stack) > 0:
    cur = stack.pop()
    for [i, j] in step2:
        ny, nx = cur[0] + i, cur[1] + j
        if 0 <= ny < h and 0 <= nx < w and table[ny][nx] != "#":
            if table[ny][nx] == ".":
                table[ny][nx] = table[cur[0]][cur[1]] + 1
                stack.appendleft([ny, nx])
            elif table[ny][nx] > table[cur[0]][cur[1]] + 1:
                table[ny][nx] = table[cur[0]][cur[1]] + 1
                stack.appendleft([ny, nx])

    cur2 = cur
    for i in range(4):
        ny, nx = cur2[0] + step[i], cur2[1] + step[i + 1]
        if 0 <= ny < h and 0 <= nx < w and table[ny][nx] != "#":
            if table[ny][nx] == ".":
                table[ny][nx] = table[cur2[0]][cur2[1]]
                stack.appendleft([ny, nx])
            elif table[ny][nx] > table[cur2[0]][cur2[1]]:
                table[ny][nx] = table[cur2[0]][cur2[1]]
                stack.appendleft([ny, nx])
print(-1 if table[dy][dx] == "." else table[dy][dx])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import heapq

h,w=map(int,input().split())
sy,sx=map(int,input().split())
sy-=1
sx-=1
gy,gx=map(int,input().split())
gy-=1
gx-=1
board=''
for _ in range(h):
  board+=input()
costs=[10**18]*(w*h)
costs[sy*w+sx]=0
q=[]
heapq.heappush(q,(0,sy,sx))
while len(q)!=0:
  cost,y,x=heapq.heappop(q)
  cur_pos=y*w+x
  for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
    next_pos=cur_pos+dy*w+dx
    if 0<=y+dy<h and 0<=x+dx<w and board[next_pos]=='.' and costs[next_pos]>costs[cur_pos]:
      costs[next_pos]=costs[cur_pos]
      heapq.heappush(q,(cost,y+dy,x+dx))
  for dy in range(-2,3):
    for dx in range(-2,3):
      if dy==0 and dx==0:
        continue
      next_pos=cur_pos+dy*w+dx
      if 0<=y+dy<h and 0<=x+dx<w and board[next_pos]=='.' and costs[next_pos]>costs[cur_pos]+1:
        costs[next_pos]=costs[cur_pos]+1
        heapq.heappush(q,(cost+1,y+dy,x+dx))
if costs[gy*w+gx]==10**18:
  print(-1)
else:
  print(costs[gy*w+gx])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


def solve():
    readline = sys.stdin.readline
    H, W = map(int, readline().split())
    ch, cw = map(int, readline().split())
    dh, dw = map(int, readline().split())
    S = ['#' * (W+2)]
    for _ in range(H):
        S.append('#' + readline() + '#')
    S.append('#' * (W+2))
    H += 2
    W += 2
    start = ch*W + cw
    goal = dh*W + dw
    q = deque([start])
    inf = 999_999_999
    dist = [inf] * (H*W)
    dist[start] = 0
    D = [-W, -1, 1, W]
    DY = [-2*W, -W, 0, W, 2*W]

    while q:
        x = q.popleft()
        for d in D:
            i, j = divmod(x+d, W)
            if S[i][j] == '.' and dist[x+d] > dist[x]:
                q.appendleft(x+d)
                dist[x+d] = dist[x]
    
        for dy in DY:
            for dx in range(-2, 3):
                xx = x + dy + dx
                i, j = divmod(xx, W)
                if 0 <= xx < W*H and dist[xx] > dist[x] and S[i][j] == '.':
                    q.append(xx)
                    dist[xx] = dist[x] + 1
    return dist[goal] if dist[goal] != inf else -1


if __name__ == '__main__':
    ans = solve()
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import heapq

h,w=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
board=[['#']*(w+2)]+[list('#'+input()+'#') for _ in range(h)]+[['#']*(w+2)]
costs=[[10**18]*(w+1) for _ in range(h+1)]
costs[sy][sx]=0
q=[]
heapq.heappush(q,(0,sy,sx))
while len(q)!=0:
  cost,y,x=heapq.heappop(q)
  for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
    if 1<=y+dy<=h and 1<=x+dx<=w and board[y+dy][x+dx]=='.' and costs[y+dy][x+dx]>costs[y][x]:
      costs[y+dy][x+dx]=costs[y][x]
      heapq.heappush(q,(cost,y+dy,x+dx))
  for dy in range(-2,3):
    for dx in range(-2,3):
      if dy==0 and dx==0:
        continue
      if 1<=y+dy<=h and 1<=x+dx<=w and board[y+dy][x+dx]=='.' and costs[y+dy][x+dx]>costs[y][x]+1:
        costs[y+dy][x+dx]=costs[y][x]+1
        heapq.heappush(q,(cost+1,y+dy,x+dx))
if costs[gy][gx]==10**18:
  print(-1)
else:
  print(costs[gy][gx])

Submission status: Time Limit Exceeded

Solution code:
from heapq import *
from sys import stdin
input=stdin.readline
n,m=map(int,input().split())
a,b=map(int,input().split())
x,y=map(int,input().split())
x=x-1
y=y-1
arr=[]
from math import inf
for i in range(n):
    arr.append(list(input().strip()))
def isvalid(x,y):
    if x<0 or y<0 or x>=n or y>=m or arr[x][y]=="#" :
        return False
    return True
vis=[[0]*m for i in range(n)]
stack=[[0,a-1,b-1]]
heapify(stack)
if x==a-1 and y==b-1 and arr[x][y]=="#":
    print(-1)
    quit()
mi=inf
ans=[[inf]*m for i in range(n)]
while(stack):
    cost,xx,yy=heappop(stack)
    ans[xx][yy]=cost
    if xx==x and yy==y:
        mi=min(mi,cost)
        break
    for i in [[-1,0],[1,0],[0,1],[0,-1]]:
        if isvalid(xx+i[0],yy+i[1]):
            if ans[xx+i[0]][yy+i[1]]>cost:
                heappush(stack,[cost,xx+i[0],yy+i[1]])
    for i in range(-2,3):
        for j in range(-2,3):
            if isvalid(xx+i,yy+j):
                if ans[xx+i][yy+j]>cost+1:
                    heappush(stack,[cost+1,xx+i,yy+j])
       
if mi==inf:
    print(-1)
else:
    print(mi)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


def solve():
    readline = sys.stdin.readline
    H, W = map(int, readline().split())
    ch, cw = map(int, readline().split())
    dh, dw = map(int, readline().split())
    S = ['#'] * (W+2)
    for _ in range(H):
        S += ['#'] + list(readline().rstrip()) + ['#']
    S += ['#'] * (W+2)
    H += 2
    W += 2
    start = ch*W + cw
    goal = dh*W + dw
    q = deque([start])
    inf = 999_999_999
    dist = [inf] * (H*W)
    dist[start] = 0
    D = [-W, -1, 1, W]
    DY = [-2*W, -W, 0, W, 2*W]

    while q:
        x = q.popleft()
        for d in D:
            if S[x+d] == '.' and dist[x+d] > dist[x]:
                q.appendleft(x+d)
                dist[x+d] = dist[x]
    
        for dy in DY:
            for dx in range(-2, 3):
                xx = x + dy + dx
                if 0 <= xx < W*H and dist[xx] > dist[x] and S[xx] == '.':
                    q.append(xx)
                    dist[xx] = dist[x] + 1
    return dist[goal] if dist[goal] != inf else -1


if __name__ == '__main__':
    ans = solve()
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

import heapq

h,w=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
board=[['#']*(w+2)]+[list('#'+input()+'#') for _ in range(h)]+[['#']*(w+2)]
costs=[[10**18]*(w+1) for _ in range(h+1)]
costs[sy][sx]=0
q=[]
heapq.heappush(q,(0,sy,sx))
while len(q)!=0:
  cost,y,x=heapq.heappop(q)
  if y==gy and x==gx:
    print(cost)
    exit()
  for dy,dx in [[-1,0],[1,0],[0,-1],[0,1]]:
    if 1<=y+dy<=h and 1<=x+dx<=w and board[y+dy][x+dx]=='.' and costs[y+dy][x+dx]>costs[y][x]:
      costs[y+dy][x+dx]=costs[y][x]
      heapq.heappush(q,(cost,y+dy,x+dx))
  for dy in range(-2,3):
    for dx in range(-2,3):
      if dy==0 and dx==0:
        continue
      if 1<=y+dy<=h and 1<=x+dx<=w and board[y+dy][x+dx]=='.' and costs[y+dy][x+dx]>costs[y][x]+1:
        costs[y+dy][x+dx]=costs[y][x]+1
        heapq.heappush(q,(cost+1,y+dy,x+dx))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


def solve():
    readline = sys.stdin.readline
    H, W = map(int, readline().split())
    ch, cw = map(int, readline().split())
    dh, dw = map(int, readline().split())
    S = ['#'] * (W+2)
    for _ in range(H):
        S += ['#'] + list(readline().rstrip()) + ['#']
    S += ['#'] * (W+2)
    H += 2
    W += 2
    now = ch*W + cw
    goal = dh*W + dw
    q = deque([now])
    inf = 999_999_999
    dist = [inf] * (H*W)
    dist[now] = 0
    D = [-W, -1, 1, W]
    DY = [-2*W, -W, 0, W, 2*W]

    while q:
        x = q.popleft()
        for d in D:
            if S[x+d] == '.' and dist[x+d] > dist[x]:
                q.appendleft(x+d)
                dist[x+d] = dist[x]
    
        for dy in DY:
            for dx in range(-2, 3):
                xx = x + dy + dx
                if 0 <= xx < W*H and dist[xx] > dist[x] and S[xx] == '.':
                    q.append(xx)
                    dist[xx] = dist[x] + 1
    return dist[goal] if dist[goal] != inf else -1


if __name__ == '__main__':
    ans = solve()
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W = map(int,input().split())
CH,CW = map(int,input().split())
DH,DW = map(int,input().split())
stage = [[-1 for w in range(W)] for h in range(H)]
for h in range(H):
    S = input()
    for w,s in enumerate(S):
        if s=='#':
            stage[h][w] = -2
H -= 1;W -= 1; CH -= 1; CW -= 1; DH -= 1; DW -= 1
from collections import deque
Q = deque([[CH,CW,0]])
while Q:
    qh,qw,qc = Q.popleft()
    for h in range(-2,3):
        for w in range(-2,3):
            # 移動なしは無視
            if h==0 and w == 0:
                pass
            # 場外判定
            elif qh+h < 0 or qh+h > H or qw + w < 0 or qw + w > W:
                pass
            # 普通の移動
            elif (h==0 and w==1) or (h==1 and w==0) or (h==0 and w==-1) or (h==-1 and w==0):
                # 未移動の場合 or 移動済の場合
                if stage[qh+h][qw+w] == -1 or stage[qh+h][qw+w] > qc:
                    stage[qh+h][qw+w] = qc
                    Q.append([qh+h,qw+w,qc])
            # ワープの移動
            else:
                if stage[qh+h][qw+w] == -1 or stage[qh+h][qw+w] > qc+1:
                    stage[qh+h][qw+w] = qc + 1
                    Q.append([qh+h,qw+w,qc+1])
print(stage[DH][DW])

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

dd = [(1,0),(0,1),(-1,0),(0,-1)]
h,w = inpl()
cy,cx = inpl()
gy,gx = inpl()
cy,cx,gy,gx = cy-1,cx-1,gy-1,gx-1
s = [input() for _ in range(h)]
res = [INF] * (h*w)
q = deque([(cy,cx)])
res[cy*w+cx] = 0
while q:
    oy,ox = q.popleft()
    for dy in range(-2,3):
        for dx in range(-2,3):
            ny = dy + oy
            nx = dx + ox
            if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == '.':
                f = False
                if (dy,dx) in dd:
                    if res[ny*w+nx] > res[oy*w+ox]:
                        f = True
                        res[ny*w+nx] = min(res[ny*w+nx], res[oy*w+ox])
                else:
                    if res[ny*w+nx] > res[oy*w+ox] + 1:
                        f = True
                        res[ny*w+nx] = min(res[ny*w+nx], res[oy*w+ox] + 1)
                if f: q.append((ny,nx))
print(res[gy*w+gx] if res[gy*w+gx] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
import sys


def solve():
    readline = sys.stdin.readline
    H, W = map(int, readline().split())
    ch, cw = map(int, readline().split())
    dh, dw = map(int, readline().split())
    S = ['#'] * (W+2)
    for _ in range(H):
        S += ['#'] + list(readline().rstrip()) + ['#']
    S += ['#'] * (W+2)
    H += 2
    W += 2
    now = ch*W + cw
    goal = dh*W + dw
    q = [now]
    inf = 999_999_999
    dist = [inf] * (H*W)
    dist[now] = 0
    D = [-W, -1, 1, W]
    DY = [-2*W, -W, 0, W, 2*W]

    while q:
        x = q.pop()
        for d in D:
            if S[x+d] == '.' and dist[x+d] > dist[x]:
                q.append(x+d)
                dist[x+d] = dist[x]
    
        for dy in DY:
            for dx in range(-2, 3):
                xx = x + dy + dx
                if 0 <= xx < W*H and dist[xx] > dist[x] and S[xx] == '.':
                    q.append(xx)
                    dist[xx] = dist[x] + 1
    return dist[goal] if dist[goal] != inf else -1


if __name__ == '__main__':
    ans = solve()
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W = map(int,input().split())
CH,CW = map(int,input().split())
DH,DW = map(int,input().split())
stage = [[-1 for w in range(W)] for h in range(H)]
for h in range(H):
    S = input()
    for w,s in enumerate(S):
        if s=='#':
            stage[h][w] = -2
H -= 1;W -= 1; CH -= 1; CW -= 1; DH -= 1; DW -= 1
from collections import deque
Q = deque([[CH,CW,0]])
while Q:
    qh,qw,qc = Q.popleft()
    for h in range(-2,3):
        for w in range(-2,3):
            # 移動なしは無視
            if h==0 and w == 0:
                pass
            # 場外判定
            elif qh+h < 0 or qh+h > H or qw + w < 0 or qw + w > W:
                pass
            # 普通の移動
            elif (h==0 and w==1) or (h==1 and w==0) or (h==0 and w==-1) or (h==-1 and w==0):
                # 未移動の場合 or 移動済の場合
                if stage[qh+h][qw+w] == -1 or stage[qh+h][qw+w] > qc:
                    stage[qh+h][qw+w] = qc
                    Q.append([qh+h,qw+w,qc])
            # ワープの移動
            else:
                if stage[qh+h][qw+w] == -1 or stage[qh+h][qw+w] > qc+1:
                    stage[qh+h][qw+w] = qc + 1
                    Q.append([qh+h,qw+w,qc+1])
print(stage[DH][DW])

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())
stage = [[-1 for w in range(W)] for h in range(H)]
for h in range(H):
    S = input()
    for w,s in enumerate(S):
        if s=='#':
            stage[h][w] = -2
H -= 1;W -= 1; CH -= 1; CW -= 1; DH -= 1; DW -= 1
from collections import deque
Q = deque([[CH,CW,0]])
while Q:
    qh,qw,qc = Q.popleft()
    for h in range(-2,3):
        for w in range(-2,3):
            # 移動なしは無視
            if h==0 and w == 0:
                pass
            # 場外判定
            elif qh+h < 0 or qh+h > H or qw + w < 0 or qw + w > W:
                pass
            # 普通の移動
            elif (h==0 and w==1) or (h==1 and w==0) or (h==0 and w==-1) or (h==-1 and w==0):
                # 未移動の場合 or 移動済の場合
                if stage[qh+h][qw+w] == -1 or stage[qh+h][qw+w] > qc:
                    stage[qh+h][qw+w] = qc
                    Q.append([qh+h,qw+w,qc])
            # ワープの移動
            else:
                if stage[qh+h][qw+w] == -1 or stage[qh+h][qw+w] > qc+1:
                    stage[qh+h][qw+w] = qc + 1
                    Q.append([qh+h,qw+w,qc+1])
print(stage[DH][DW])

Submission status: Time Limit Exceeded

Solution code:
import sys


def solve():
    readline = sys.stdin.readline
    H, W = map(int, readline().split())
    ch, cw = map(int, readline().split())
    dh, dw = map(int, readline().split())
    S = ['#'] * (W+2)
    for _ in range(H):
        S += ['#'] + list(readline().rstrip()) + ['#']
    S += ['#'] * (W+2)
    H += 2
    W += 2
    now = ch*W + cw
    goal = dh*W + dw
    q = [now]
    inf = 999_999_999
    dist = [inf] * (H*W)
    dist[now] = 0

    while q:
        x = q.pop()
        for d in [-W, -1, 1, W]:
            if S[x+d] == '.' and dist[x+d] > dist[x]:
                q.append(x+d)
                dist[x+d] = dist[x]
    
        for dy in [-2*W, -W, 0, W, 2*W]:
            for dx in range(-2, 3):
                xx = x + dy + dx
                if 0 <= xx < W*H and dist[xx] > dist[x] and S[xx] == '.':
                    q.append(xx)
                    dist[xx] = dist[x] + 1
    return dist[goal] if dist[goal] != inf else -1


if __name__ == '__main__':
    ans = solve()
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
import numba
from numba import jit

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = np.array([input() for i in range(H)])

queue = deque()
queue.append((Ch-1, Cw-1, 0))
inf = float("inf")
table = np.array([[inf] * W for i in range(H)])
table[Ch-1][Cw-1] = 0
walk_move = ((-1, 0), (0, -1), (1, 0), (0, 1))
magic_move = []
for i in range(-2, 3):
  for j in range(-2, 3):
    if not i and not j:
      continue
    else:
      magic_move.append([i, j])
@jit
def main():
  while queue:
    x, y, cost = queue.popleft()
    for i,j in walk_move:
      dx = x+i
      dy = y+j
      if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost:
        queue.appendleft((dx, dy, cost))
        table[dx][dy] = cost
    for k,l in magic_move:
      dx = x+k
      dy = y+l
      if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost+1:
        queue.append((dx, dy, cost+1))
        table[dx][dy] = cost+1
  return table[Dh-1][Dw-1]

ans = main()
if ans == inf:
  print("-1")
else:
  print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

dd = [(1,0),(0,1),(-1,0),(0,-1)]
h,w = inpl()
cy,cx = inpl()
gy,gx = inpl()
cy,cx,gy,gx = cy-1,cx-1,gy-1,gx-1
s = [input() for _ in range(h)]
res = [[INF] * w for _ in range(h)]
res[cy][cx] = 0
seen = set()
seen.add((cy,cx))
q = deque([(cy,cx)])
while q:
    oy,ox = q.popleft()
    for dy,dx in dd:
        ny = oy+dy; nx = ox+dx
        if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == '.' and not (ny,nx) in seen:
            seen.add((ny,nx))
            if res[ny][nx] > res[oy][ox]:
                res[ny][nx] = res[oy][ox]
                q.appendleft((ny,nx))
        for dy in range(-2,3):
            for dx in range(-2,3):
                ny = oy+dy; nx = ox+dx
                if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == '.':
                    if res[ny][nx] > res[oy][ox] + 1:
                        res[ny][nx] = res[oy][ox] + 1
                        q.append((ny,nx))
ans = res[gy][gx]
print(-1 if ans  == INF else ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stdin

def bfs():
    readline=stdin.readline
    h,w=map(int,readline().split())
    sy,sx=map(int,readline().split())
    gy,gx=map(int,readline().split())
    sy-=1;sx-=1;gy-=1;gx-=1
    s=[list(readline()) for _ in range(h)]
    dict={".":10000000,"#":-1}
    s=[[dict[s[y][x]] for x in range(w)]for y in range(h)]
    s[sy][sx]=0
    que=deque([[sy,sx]])
    temp=[i for i in range(-2,3)]
    while que:
        y,x=que.popleft()
        s1=s[y][x]
        for i in temp:
            nexty=y+i
            if 0<=nexty<h:
                s2=s[nexty]
                for j in temp:
                    nextx=x+j
                    if 0<=nextx<w and s[nexty][nextx]>=0:
                        dist=s2[nextx]
                        if i*i+j*j<=1 and dist>s1:
                            s[nexty][nextx]=s1
                            que.append([nexty,nextx])
                        elif dist>s1+1:
                            s[nexty][nextx]=s1+1
                            que.append([nexty,nextx])

    if s[gy][gx]==10000000:
        print(-1)
    else:
        print(s[gy][gx])
bfs()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
H,W = map(int,input().split())
CH,CW = map(int,input().split())
DH,DW = map(int,input().split())
stage = np.zeros((H,W),dtype=np.int32)
for h in range(H):
    S = input()
    for w,s in enumerate(S):
        if s=='#':
            stage[h,w] = -1
stage -= 1
H -= 1;W -= 1; CH -= 1; CW -= 1; DH -= 1; DW -= 1
from collections import deque
Q = deque([[CH,CW,0]])
while Q:
    qh,qw,qc = Q.popleft()
    for h in range(-2,3):
        for w in range(-2,3):
            # 移動なしは無視
            if h==0 and w == 0:
                pass
            # 場外判定
            elif qh+h < 0 or qh+h > H or qw + w < 0 or qw + w > W:
                pass
            # 普通の移動
            elif (h==0 and w==1) or (h==1 and w==0) or (h==0 and w==-1) or (h==-1 and w==0):
                # 未移動の場合 or 移動済の場合
                if stage[qh+h,qw+w] == -1 or stage[qh+h,qw+w] > qc:
                    stage[qh+h,qw+w] = qc
                    Q.append([qh+h,qw+w,qc])
            # ワープの移動
            else:
                if stage[qh+h,qw+w] == -1 or stage[qh+h,qw+w] > qc+1:
                    stage[qh+h,qw+w] = qc + 1
                    Q.append([qh+h,qw+w,qc+1])
print(stage[DH,DW])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from sys import stdin

def bfs():
    readline=stdin.readline
    h,w=map(int,readline().split())
    sy,sx=map(int,readline().split())
    gy,gx=map(int,readline().split())
    sy-=1;sx-=1;gy-=1;gx-=1
    s=[list(readline()) for _ in range(h)]
    dict={".":10000000,"#":-1}
    s=[[dict[s[y][x]] for x in range(w)]for y in range(h)]
    s[sy][sx]=0
    que=deque([[sy,sx]])
    temp=[(i,j) for i in range(-2,3) for j in range(-2,3)]
    while que:
        y,x=que.popleft()
        s1=s[y][x]
        for (i,j) in temp:
            nexty,nextx=y+i,x+j
            if 0<=nexty<h and 0<=nextx<w and s[nexty][nextx]>=0:
                dist=s[nexty][nextx]
                if i*i+j*j<=1 and dist>s1:
                    s[nexty][nextx]=s1
                    que.append([nexty,nextx])
                elif dist>s1+1:
                    s[nexty][nextx]=s1+1
                    que.append([nexty,nextx])

    if s[gy][gx]==10000000:
        print(-1)
    else:
        print(s[gy][gx])
bfs()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import numba
from numba import jit

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [input() for i in range(H)]

queue = deque()
queue.append((Ch-1, Cw-1, 0))
inf = float("inf")
table = [[inf] * W for i in range(H)]
table[Ch-1][Cw-1] = 0
walk_move = ((-1, 0), (0, -1), (1, 0), (0, 1))
magic_move = []
for i in range(-2, 3):
  for j in range(-2, 3):
    if not i and not j:
      continue
    else:
      magic_move.append([i, j])
@jit
def main():
  while queue:
    x, y, cost = queue.popleft()
    for i,j in walk_move:
      dx = x+i
      dy = y+j
      if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost:
        queue.appendleft((dx, dy, cost))
        table[dx][dy] = cost
    for k,l in magic_move:
      dx = x+k
      dy = y+l
      if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost+1:
        queue.append((dx, dy, cost+1))
        table[dx][dy] = cost+1
  return table[Dh-1][Dw-1]

ans = main()
if ans == inf:
  print("-1")
else:
  print(table[Dh-1][Dw-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 = [input() for i in range(H)]

queue = deque()
queue.append((Ch-1, Cw-1, 0))
inf = float("inf")
table = [[inf] * W for i in range(H)]
table[Ch-1][Cw-1] = 0
walk_move = ((-1, 0), (0, -1), (1, 0), (0, 1))
magic_move = []
for i in range(-2, 3):
  for j in range(-2, 3):
    if not i and not j:
      continue
    else:
      magic_move.append([i, j])

while queue:
  x, y, cost = queue.popleft()
  for i,j in walk_move:
    dx = x+i
    dy = y+j
    if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost:
      queue.appendleft((dx, dy, cost))
      table[dx][dy] = cost
  for k,l in magic_move:
    dx = x+k
    dy = y+l
    if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost+1:
      queue.append((dx, dy, cost+1))
      table[dx][dy] = cost+1

ans = table[Dh-1][Dw-1]
if ans == inf:
  print("-1")
else:
  print(table[Dh-1][Dw-1])