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:
h, w = list(map(int, input().split()))
si, sj = list(map(int, input().split()))
ti, tj = list(map(int, input().split()))
s = [None] * h
for i in range(h):
    s[i] = input()

# 移動Aで探索する方向
d_a = [(-1,0), (0,-1),(1,0),(0,1)]
# 移動Bで探索する方向
d_b = [ (i, j) for j in range(-2, 3) for i in range(-2, 3)]

# 距離情報を一番遠い値で初期化
#import numpy as np
INF = int(1e9)
#dist = np.full((h+4, w+4), INF)
dist = [[INF for j in range(w+4)] for i in range(h+4)]

# マップ境界と壁を距離0にして探索させない
for i in range(len(dist)):
    dist[i][0] = 0
    dist[i][1] = 0
    dist[i][-1] = 0
    dist[i][-2] = 0
for j in range(len(dist[0])):
    dist[0][j] = 0
    dist[1][j] = 0
    dist[-1][j] = 0
    dist[-2][j] = 0
for i in range(h):
    for j in range(w):
        if s[i][j]=='#': dist[i+2][j+2] = 0

# 01-BFS探索用キュー
from collections import deque
q = deque()

# 開始位置、終了位置を調整
si, sj = si+1, sj+1
ti, tj = ti+1, tj+1
dist[si][sj] = 0
q.append((si,sj))

while (len(q)>0):
    i, j = q[0]
    d = dist[i][j]
    q.popleft()
    # 移動Aによるコスト
    for v in range(len(d_a)):
        di, dj = d_a[v][0]+i, d_a[v][1]+j
        if (di, dj) == (ti, tj):
            print(d)
            exit(0)
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d
        q.appendleft((di, dj))
    # 移動Bによるコスト
    for v in range(len(d_b)):
        di, dj = d_b[v][0]+i, d_b[v][1]+j
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d+1
        q.append((di, dj))

ans = dist[ti][tj]
if ans == INF:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split()))
si, sj = list(map(int, input().split()))
ti, tj = list(map(int, input().split()))
s = [None] * h
for i in range(h):
    s[i] = input()

# 移動Aで探索する方向
d_a = [(-1,0), (0,-1),(1,0),(0,1)]
# 移動Bで探索する方向
d_b = [ (i, j) for j in range(-2, 3) for i in range(-2, 3)]

# 距離情報を一番遠い値で初期化
import numpy as np
INF = int(1e9)
dist = np.full((h+2, w+2), INF)
#dist = [[INF for j in range(w+2)] for i in range(h+2)]

# マップ境界と壁を距離0にして探索させない
for i in range(h+2):
    dist[i][0] = 0
    dist[i][-1] = 0
for j in range(w+2):
    dist[0][j] = 0
    dist[-1][j] = 0
for i in range(h):
    for j in range(w):
        if s[i][j]=='#': dist[i+1][j+1] = 0
#dist = [[INF for j in range(w)] for i in range(h)]

# 01-BFS探索用キュー
from collections import deque
q = deque()

# 開始位置
dist[si][sj] = 0
q.append((si,sj))

while (len(q)>0):
    i, j = q[0]
    d = dist[i][j]
    q.popleft()
    # 移動Aによるコスト
    for v in range(len(d_a)):
        di, dj = d_a[v][0]+i, d_a[v][1]+j
        if (di, dj) == (ti, tj):
            print(d)
            exit(0)
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d
        q.appendleft((di, dj))
    # 移動Bによるコスト
    for v in range(len(d_b)):
        # マップ境界で2以上移動したときに、反対の境界に向かうように剰余を取る
        di, dj = (d_b[v][0]+i)%(h+2), (d_b[v][1]+j)%(w+2)
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d+1
        q.append((di, dj))

ans = dist[ti][tj]
if ans == INF:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split()))
si, sj = list(map(int, input().split()))
ti, tj = list(map(int, input().split()))
s = [None] * h
for i in range(h):
    s[i] = input()

# 移動Aで探索する方向
d_a = [(-1,0), (0,-1),(1,0),(0,1)]
# 移動Bで探索する方向
d_b = [ (i, j) for j in range(-2, 3) for i in range(-2, 3)]

# 距離情報を一番遠い値で初期化
#import numpy as np
INF = int(1e9)
#dist = np.full((h+2, w+2), INF)
dist = [[INF for j in range(w+2)] for i in range(h+2)]

# マップ境界と壁を距離0にして探索させない
for i in range(h+2):
    dist[i][0] = 0
    dist[i][-1] = 0
for j in range(w+2):
    dist[0][j] = 0
    dist[-1][j] = 0
for i in range(h):
    for j in range(w):
        if s[i][j]=='#': dist[i+1][j+1] = 0
#dist = [[INF for j in range(w)] for i in range(h)]

# 01-BFS探索用キュー
from collections import deque
q = deque()

# 開始位置
dist[si][sj] = 0
q.append((si,sj))

while (len(q)>0):
    i, j = q[0]
    d = dist[i][j]
    q.popleft()
    # 移動Aによるコスト
    for v in range(len(d_a)):
        di, dj = d_a[v][0]+i, d_a[v][1]+j
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d
        q.appendleft((di, dj))
    # 移動Bによるコスト
    for v in range(len(d_b)):
        # マップ境界で2以上移動したときに、反対の境界に向かうように剰余を取る
        di, dj = (d_b[v][0]+i)%(h+2), (d_b[v][1]+j)%(w+2)
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d+1
        q.append((di, dj))

ans = dist[ti][tj]
if ans == INF:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split()))
si, sj = list(map(int, input().split()))
ti, tj = list(map(int, input().split()))
s = [None] * h
for i in range(h):
    s[i] = input()

# 移動Aで探索する方向
d_a = [(-1,0), (0,-1),(1,0),(0,1)]
# 移動Bで探索する方向
d_b = [ (i, j) for j in range(-2, 3) for i in range(-2, 3)]

# 距離情報を一番遠い値で初期化
import numpy as np
INF = int(1e9)
dist = np.full((h+2, w+2), INF)

# マップ境界と壁を距離0にして探索させない
for i in range(h+2):
    dist[i, 0] = 0
    dist[i, -1] = 0
for j in range(w+2):
    dist[0, j] = 0
    dist[-1, j] = 0
for i in range(h):
    for j in range(w):
        if s[i][j]=='#': dist[i+1][j+1] = 0
#dist = [[INF for j in range(w)] for i in range(h)]

# 01-BFS探索用キュー
from collections import deque
q = deque()

# 開始位置
dist[si][sj] = 0
q.append((si,sj))

while (len(q)>0):
    i, j = q[0]
    d = dist[i][j]
    q.popleft()
    # 移動Aによるコスト
    for v in range(len(d_a)):
        di, dj = d_a[v][0]+i, d_a[v][1]+j
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d
        q.appendleft((di, dj))
    # 移動Bによるコスト
    for v in range(len(d_b)):
        # マップ境界で2以上移動したときに、反対の境界に向かうように剰余を取る
        di, dj = (d_b[v][0]+i)%(h+2), (d_b[v][1]+j)%(w+2)
        if (dist[di][dj]<=d):
            continue # 探索済みコスト以上
        dist[di][dj] = d+1
        q.append((di, dj))

ans = dist[ti][tj]
if ans == INF:
    ans = -1
print(ans)

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=[list(input()) for i in range(h)]

#幅優先で解く。
dx=[1,0,-1,0]
dy=[0,1,0,-1]
def bfs():
  maze=[[-1]*w for i in range(h)]
  maze[ch-1][cw-1]=0
  qu=deque([])
  qu.append((cw-1,ch-1))
  magic=0
  
  while qu:
    x,y=qu.popleft()
    for i in range(x-2,x+3):
      for j in range(y-2,y+3):
        nx=i
        ny=j
        if 0<=nx<=w-1 and 0<=ny<=h-1 and s[ny][nx]=="." and (maze[ny][nx]==-1 or maze[ny][nx]>maze[y][x]+1):
          qu.append((nx,ny))
          maze[ny][nx]=maze[y][x]+1
    for i in range(4):
      nx=dx[i]+x
      ny=dy[i]+y
      
      if 0<=nx<=w-1 and 0<=ny<=h-1 and s[ny][nx]=="." and (maze[ny][nx]==-1 or maze[ny][nx]>maze[y][x]):
        qu.appendleft((nx,ny))
        maze[ny][nx]=maze[y][x]
  return maze
    
maze = bfs()
print(maze[dh-1][dw-1])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
import queue
    
def BFS(c,t,Num):
    q = queue.Queue()
    q.put(c)
    
    while not q.empty(): 
        n = q.get()
        if t[n[0] + 1][n[1]] != -1 and t[n[0] + 1][n[1]] == 9999:
            q.put([n[0] + 1, n[1]])
            t[n[0] + 1][n[1]] = Num
    
        if t[n[0]][n[1] + 1] != -1 and t[n[0]][n[1] + 1] == 9999:
            q.put([n[0], n[1] + 1])
            t[n[0]][n[1] + 1] = Num
        
        if t[n[0] - 1][n[1]] != -1 and t[n[0] - 1][n[1]] == 9999:
            q.put([n[0] - 1, n[1] ])
            t[n[0] - 1][ n[1] ] = Num

        if t[n[0]][n[1] - 1] != -1 and t[n[0]][n[1] - 1] == 9999:
            q.put([n[0],n[1] - 1])
            t[n[0]][n[1] - 1] = Num  


def SearchNum(t, Num):
    q = queue.Queue()    
    for i in range(H + 4):
        for j in range(W + 4):
            if t[i][j] == Num:
                q.put([i,j])            
    return q

def Warp(c,t,Num):
    for i in range(c[0]-2,c[0]+3):
        for j in range(c[1]-2,c[1]+3):
            if t[i][j] == 9999:
                t[i][j] = Num
    
H, W = map(int,input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = []
for i in range(H):    
  S.append(list(input()))

C[0] -= 1
C[1] -= 1
D[0] -= 1
D[1] -= 1

T = np.full([H + 4,W + 4],-1)

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)
count = 0
while True:      
    
    c = 0
    for i in range(H + 4):
        for j in range(W + 4):
            if T[i][j] == count:
                Warp([i,j],T,count + 1)
                c += 1
    if(c == 0):
        break
    
    count += 1 
        
    for i in range(H + 4):
        for j in range(W + 4):
            if T[i][j] == count:
                BFS([i,j],T,count)
        
    if count > 1500:
        print("miss")
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break
    

if T[D[0] + 2][D[1] + 2] != 9999:
    print(T[D[0] + 2][D[1] + 2])
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
import queue
    
def BFS(c,t,Num):
    q = queue.Queue()
    q.put(c)
    
    while not q.empty(): 
        n = q.get()
        if t[n[0] + 1][n[1]] != -1 and t[n[0] + 1][n[1]] == 9999:
            q.put([n[0] + 1, n[1]])
            t[n[0] + 1][n[1]] = Num
    
        if t[n[0]][n[1] + 1] != -1 and t[n[0]][n[1] + 1] == 9999:
            q.put([n[0], n[1] + 1])
            t[n[0]][n[1] + 1] = Num
        
        if t[n[0] - 1][n[1]] != -1 and t[n[0] - 1][n[1]] == 9999:
            q.put([n[0] - 1, n[1] ])
            t[n[0] - 1][ n[1] ] = Num

        if t[n[0]][n[1] - 1] != -1 and t[n[0]][n[1] - 1] == 9999:
            q.put([n[0],n[1] - 1])
            t[n[0]][n[1] - 1] = Num  


def SearchNum(t, Num):
    q = queue.Queue()    
    for i in range(H + 4):
        for j in range(W + 4):
            if t[i][j] == Num:
                q.put([i,j])            
    return q

def Warp(c,t,Num):
    for i in range(c[0]-2,c[0]+3):
        for j in range(c[1]-2,c[1]+3):
            if t[i][j] == 9999:
                t[i][j] = Num
    
H, W = map(int,input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = []
for i in range(H):    
  S.append(list(input()))

C[0] -= 1
C[1] -= 1
D[0] -= 1
D[1] -= 1

T = np.full([H + 4,W + 4],-1)

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)
count = 0
while True:      
    
    c = 0
    for i in range(H + 4):
        for j in range(W + 4):
            if T[i][j] == count:
                Warp([i,j],T,count + 1)
                c += 1
    if(c == 0):
        break
    
    count += 1 
        
    for i in range(H + 4):
        for j in range(W + 4):
            if T[i][j] == count:
                BFS([i,j],T,count)
        
    if count > 1500:
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break
    

if T[D[0] + 2][D[1] + 2] != 9999:
    print(T[D[0] + 2][D[1] + 2])
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import numpy as np
import queue
    
def BFS(c,t,Num):
    q = queue.Queue()
    q.put(c)
    
    while not q.empty(): 
        n = q.get()
        if t[n[0] + 1][n[1]] != -1 and t[n[0] + 1][n[1]] == 9999:
            q.put([n[0] + 1, n[1]])
            t[n[0] + 1][n[1]] = Num
    
        if t[n[0]][n[1] + 1] != -1 and t[n[0]][n[1] + 1] == 9999:
            q.put([n[0], n[1] + 1])
            t[n[0]][n[1] + 1] = Num
        
        if t[n[0] - 1][n[1]] != -1 and t[n[0] - 1][n[1]] == 9999:
            q.put([n[0] - 1, n[1] ])
            t[n[0] - 1][ n[1] ] = Num

        if t[n[0]][n[1] - 1] != -1 and t[n[0]][n[1] - 1] == 9999:
            q.put([n[0],n[1] - 1])
            t[n[0]][n[1] - 1] = Num  


def SearchNum(t, Num):
    q = queue.Queue()    
    for i in range(H + 4):
        for j in range(W + 4):
            if t[i][j] == Num:
                q.put([i,j])            
    return q

def Warp(c,t,Num):
    for i in range(c[0]-2,c[0]+3):
        for j in range(c[1]-2,c[1]+3):
            if t[i][j] == 9999:
                t[i][j] = Num
    
H, W = map(int,input().split())
C = list(map(int,input().split()))
D = list(map(int,input().split()))
S = []
for i in range(H):    
  S.append(list(input()))

C[0] -= 1
C[1] -= 1
D[0] -= 1
D[1] -= 1

T = np.full([H + 4,W + 4],-1)

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)
count = 0
while True:      
    
    c = 0
    for i in range(H + 4):
        for j in range(W + 4):
            if T[i][j] == count:
                Warp([i,j],T,count + 1)
                c += 1
    if(c == 0):
        break
    
    count += 1 
        
    q_BFS = SearchNum(T,count)
    while not q_BFS.empty():
        n2 = q_BFS.get()
        BFS(n2,T,count)
        
    if count > 1500:
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break
    

if T[D[0] + 2][D[1] + 2] != 9999:
    print(T[D[0] + 2][D[1] + 2])
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
d = deque() # 初期化

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

d.appendleft((Ch-1, Cw-1))
score = dict()
score[(Ch-1, Cw-1)] = 0

walk = [(-1, 0), (1, 0), (0, -1), (0, 1)]
warp = list()
for i in range(-2, 3):
  for j in range(-2, 3):
    if (i, j) != (0, 0) and (i, j) not in walk:
      warp.append((i, j))

while len(d) > 0:
  
  # walk
  y, x = d.popleft()
  for i in range(len(walk)):
    dy, dx = walk[i]
    if 0 <= y+dy < H and 0 <= x+dx < W: 
      if (y+dy, x+dx) not in score or ((y+dy, x+dx) in score and score[y+dy, x+dx] > score[y, x]):
        if Shw[y+dy][x+dx] == ".":
          d.appendleft((y+dy, x+dx))
          score[(y+dy, x+dx)] = score[(y, x)]
          
  # warp
  for i in range(len(warp)):
    dy, dx = warp[i]
    if 0 <= y+dy < H and 0 <= x+dx < W:
      if (y+dy, x+dx) not in score or ((y+dy, x+dx) in score and score[y+dy, x+dx] > score[y, x]+1):
        if Shw[y+dy][x+dx] == ".":
          d.append((y+dy, x+dx))
          score[(y+dy, x+dx)] = score[(y, x)]+1

if (Dh-1, Dw-1) in score:
  print(score[(Dh-1, Dw-1)])
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
d = deque()

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

d.appendleft((Ch-1, Cw-1))
score = dict()
score[(Ch-1, Cw-1)] = 0

while len(d) > 0:
  
  here = d.popleft()
      
  # 右のマス
  if here[1] != W-1:
    if (here[0], here[1]+1) not in score or ((here[0], here[1]+1) in score and (score[(here[0], here[1]+1)] > score[here])):
      if Shw[here[0]][here[1]+1] == ".":
        d.appendleft((here[0], here[1]+1))
        score[(here[0], here[1]+1)] = score[here]

  # 下のマス
  if here[0] != H-1:
    if (here[0]+1, here[1]) not in score or ((here[0]+1, here[1]) in score and (score[(here[0]+1, here[1])] > score[here])):
      if Shw[here[0]+1][here[1]] == ".":
        d.appendleft((here[0]+1, here[1]))
        score[(here[0]+1, here[1])] = score[here]
  
  # 左のマス
  if here[1] != 0:
    if (here[0], here[1]-1) not in score or ((here[0], here[1]-1) in score and (score[(here[0], here[1]-1)] > score[here])):
      if Shw[here[0]][here[1]-1] == ".":
        d.appendleft((here[0], here[1]-1))
        score[(here[0], here[1]-1)] = score[here]
    
  # 上のマス
  if here[0] != 0:
    if (here[0]-1, here[1]) not in score or ((here[0]-1, here[1]) in score and (score[(here[0]-1, here[1])] > score[here])):
      if Shw[here[0]-1][here[1]] == ".":
        d.appendleft((here[0]-1, here[1]))
        score[(here[0]-1, here[1])] = score[here]
  
  # ワープのマス
  start_h = here[0]-2 if here[0]-2 > 0 else 0
  end_h = here[0]+3 if here[0] + 3 < H else H
  start_w = here[1]-2 if here[1]-2 > 0 else 0
  end_w = here[1]+3 if here[1] + 3 < W else W
  for i in range(start_h, end_h, 1):
    for j in range(start_w, end_w, 1):
      if j < 0 or j > W-1 or (i, j) in score:
        continue
      else:
        if Shw[i][j] == ".":
          d.append((i, j))
          score[(i, j)] = score[here] + 1

if (Dh-1, Dw-1) in score:
  print(score[(Dh-1, Dw-1)])
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
d = deque() # 初期化

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

d.appendleft((Ch-1, Cw-1))
score = dict()
score[(Ch-1, Cw-1)] = 0

while len(d) > 0:
  
  here = d.popleft()
      
  # 右のマス
  if here[1] != W-1:
    if (here[0], here[1]+1) not in score or ((here[0], here[1]+1) in score and (score[(here[0], here[1]+1)] > score[here])):
      if Shw[here[0]][here[1]+1] == ".":
        d.appendleft((here[0], here[1]+1))
        score[(here[0], here[1]+1)] = score[here]

  # 下のマス
  if here[0] != H-1:
    if (here[0]+1, here[1]) not in score or ((here[0]+1, here[1]) in score and (score[(here[0]+1, here[1])] > score[here])):
      if Shw[here[0]+1][here[1]] == ".":
        d.appendleft((here[0]+1, here[1]))
        score[(here[0]+1, here[1])] = score[here]
  
  # 左のマス
  if here[1] != 0:
    if (here[0], here[1]-1) not in score or ((here[0], here[1]-1) in score and (score[(here[0], here[1]-1)] > score[here])):
      if Shw[here[0]][here[1]-1] == ".":
        d.appendleft((here[0], here[1]-1))
        score[(here[0], here[1]-1)] = score[here]
    
  # 上のマス
  if here[0] != 0:
    if (here[0]-1, here[1]) not in score or ((here[0]-1, here[1]) in score and (score[(here[0]-1, here[1])] > score[here])):
      if Shw[here[0]-1][here[1]] == ".":
        d.appendleft((here[0]-1, here[1]))
        score[(here[0]-1, here[1])] = score[here]
  
  # ワープのマス
  for i in range(here[0]-2, here[0]+3, 1):
    if i < 0 or i > H-1:
      continue
    for j in range(here[1]-2, here[1]+3, 1):
      if j < 0 or j > W-1 or (i, j) in score:
        continue
      else:
        if Shw[i][j] == ".":
          d.append((i, j))
          score[(i, j)] = score[here] + 1

#print(score)
if (Dh-1, Dw-1) in score:
  print(score[(Dh-1, Dw-1)])
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
infty = 10 ** 12

def BFS(dist):
    start = (C_H-1)*W + C_W-1
    queue = deque()
    queue.append((start, 0))
    determined = [False for k in range(len(dist))] #最短距離が決まったか否か
    while queue:
        v = queue.popleft()
        if not determined[v[0]]:
            determined[v[0]] = True
            dist[v[0]] = v[1]
            row = v[0]//W
            col = v[0]%W
            for t in range(25):
                k = t//5
                l = t%5
                if t == 12:
                    continue
                elif S_extended[row + k][col + l] == "." and not determined[(row+k-2)*W + col+l-2]:
                    if (k, l) in [(1, 2), (2, 1), (2, 3), (3, 2)] and dist[(row+k-2)*W + col+l-2] > v[1]:
                        dist[(row+k-2)*W + col+l-2] = v[1]
                        queue.appendleft(((row+k-2)*W + col+l-2, v[1]))
                    else:
                        dist[(row+k-2)*W + col+l-2] = v[1]+1
                        queue.append(((row+k-2)*W + col+l-2, v[1]+1))

H, W = map(int, input().split())
C_H, C_W = map(int, input().split())
D_H, D_W = map(int, input().split())

graph = [[] for i in range(H*W)]
S = []
for i in range(H):
    S.append(input())

s = ""
for j in range (W+4):
    s += "#"
S_extended = [s, s]
for i in range(H):
    S_extended.append("##" + S[i] + "##")
S_extended.append(s)
S_extended.append(s)

dist = [infty for i in range(H*W)]
BFS(dist)
if dist[(D_H-1)*W + D_W-1] == infty:
    print("-1")
else:
    print(dist[(D_H-1)*W + D_W-1])

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from collections import deque

    h, w = map(int, input().split())
    c_h, c_w = map(int, input().split())
    c_h -= 1
    c_w -= 1
    d_h, d_w = map(int, input().split())
    d_h -= 1
    d_w -= 1
    dist = [[10**18 for i in range(w)] for i in range(h)]
    dist[c_h][c_w] = 0

    C = []
    for _ in range(h):
        C.append(list(input()))
    D = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    queue = deque([(c_h, c_w)])

    while queue:
        (x, y) = queue.popleft()
        d = dist[x][y]

        for (dx, dy) in D:
            new_x, new_y = x + dx, y + dy
            if -1 < new_x < h and -1 < new_y < w:
                if C[new_x][new_y] == '.' and dist[new_x][new_y] > d:
                    dist[new_x][new_y] = d
                    queue.appendleft((new_x, new_y))

        for dx in range(-2, 3):
            for dy in range(-2, 3):
                if -1 < x + dx < h and -1 < y + dy < w and (dx != 0 or dy != 0):
                    if C[x + dx][y + dy] == '.' and dist[x + dx][y + dy] > d:
                        dist[x + dx][y + dy] = d + 1
                        queue.append((x + dx, y + dy))

    ans = dist[d_h][d_w]
    if ans == 10**18:
        print(-1)
    else:
        print(ans)

resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
infty = 10 ** 12

def BFS(dist):
    start = (C_H-1)*W + C_W-1
    queue = deque()
    queue.append((start, 0))
    determined = [False for k in range(len(dist))] #最短距離が決まったか否か
    while queue:
        v = queue.popleft()
        if not determined[v[0]]:
            determined[v[0]] = True
            dist[v[0]] = v[1]
            row = v[0]//W
            col = v[0]%W
            for t in range(25):
                k = t//5
                l = t%5
                if t == 12:
                    continue
                elif S_extended[row + k][col + l] == "." and not determined[(row+k-2)*W + col+l-2]:
                    if (k, l) in [(1, 2), (2, 1), (2, 3), (3, 2)] and dist[(row+k-2)*W + col+l-2] > v[1]:
                        dist[(row+k-2)*W + col+l-2] = v[1]
                        queue.appendleft(((row+k-2)*W + col+l-2, v[1]))
                    else:
                        queue.append(((row+k-2)*W + col+l-2, v[1]+1))

H, W = map(int, input().split())
C_H, C_W = map(int, input().split())
D_H, D_W = map(int, input().split())

graph = [[] for i in range(H*W)]
S = []
for i in range(H):
    S.append(input())

s = ""
for j in range (W+4):
    s += "#"
S_extended = [s, s]
for i in range(H):
    S_extended.append("##" + S[i] + "##")
S_extended.append(s)
S_extended.append(s)

dist = [infty for i in range(H*W)]
BFS(dist)
if dist[(D_H-1)*W + D_W-1] == infty:
    print("-1")
else:
    print(dist[(D_H-1)*W + D_W-1])

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split()))
si, sj = list(map(lambda x: int(x)-1, input().split()))
ti, tj = list(map(lambda x: int(x)-1, input().split()))
s = [None] * h
for i in range(h):
    s[i] = input()

# 探索時に移動する方向
di = [-1, 0, 1, 0]
dj = [0, -1, 0, 1]

# 距離情報を一番遠い値で初期化
import numpy as np
INF = int(1e9)
dist = np.full((h, w), INF)
#dist = [[INF for j in range(w)] for i in range(h)]

from collections import deque
q = deque()

# 開始位置
dist[si][sj] = 0
q.append((si,sj))

while (len(q)>0):
    (i, j) = q[0]
    d = dist[i][j]
    q.popleft()
    # 移動Aによるコスト
    for v in range(len(di)):
        ni, nj = i+di[v], j+dj[v]
        if (ni<0 or ni>=h or nj<0 or nj>=w):
            continue # マップの境界
        if (s[ni][nj] == '#'):
            continue # 壁
        if (dist[ni][nj]<=d):
            continue # 探索済みコスト以上
        dist[ni][nj] = d
        q.appendleft((ni, nj))
    # 移動Bによるコスト
    for ei in range(-2, 3):
        for ej in range(-2, 3):
            ni, nj = i+ei, j+ej
            if (ni<0 or ni>=h or nj<0 or nj>=w):
                continue # マップの境界
            if (s[ni][nj] == '#'):
                continue # 壁
            if (dist[ni][nj]<=d):
                continue # 探索済みコスト以上
            dist[ni][nj] = d+1
            q.append((ni, nj))

ans = dist[ti][tj]
if ans == INF:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def warp(p,h,w):
    ls = []
    for i in range(-2,3):
        for j in range(-2,3):
            ls.append([p[0]+i,p[1]+j])
    ret = []
    for i in range(len(ls)):
        if -1<ls[i][0]<h and -1 < ls[i][1] < w:
            ret.append(ls[i])
    return ret

def main():
    h,w = map(int,input().split())
    ch,cw = map(int,input().split())
    dh,dw = map(int,input().split())
    s = []
    for i in range(h):
        s.append(input())
    dis = [[-1 for i in range(w)] for i in range(h)]
    que = [[ch-1,cw-1]]
    dis[ch-1][cw-1] = 0
    g = 0
    while len(que)>0:
        nxt = []
        while len(que)>0:
            q = que.pop(0)
            if s[q[0]][q[1]] == '#':
                continue
            nxt.append(q)
            for [mv1,mv2] in [[0,1],[0,-1],[1,0],[-1,0]]:
                if -1 < q[0]+mv1 < h and -1 < q[1]+mv2 < w:
                    if dis[q[0]+mv1][q[1]+mv2] == -1:
                        if s[q[0]+mv1][q[1]+mv2] == '.':
                            dis[q[0]+mv1][q[1]+mv2] = g
                            que.append([q[0]+mv1, q[1]+mv2])
        g += 1
        for i in range(len(nxt)):
            for [x,y] in warp(nxt[i],h,w):
                if dis[x][y] == -1:
                    if s[x][y] == '.':
                        dis[x][y] = g
                        que.append([x,y])
    print(dis[dh-1][dw-1])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
infty = 10 ** 12

def BFS(dist):
    start = (C_H-1)*W + C_W-1
    queue = deque()
    queue.append((start, 0))
    #searched = [0 for k in range(len(dist))] #探索された回数
    determined = [False for k in range(len(dist))] #最短距離が決まったか否か
    #searched[start] += 1
    while queue:
        v = queue.popleft()
        if not determined[v[0]]:
            determined[v[0]] = True
            dist[v[0]] = v[1]
            row = v[0]//W
            col = v[0]%W
            for k in range(5):
                for l in range(5):
                    if (k, l) == (2, 2):
                        continue
                    else:
                        if S_extended[row + k][col + l] == "." and not determined[(row+k-2)*W + col+l-2]:# and searched[(row+k-2)*W + col+l-2] < 2:
                            #searched[(row+k-2)*W + col+l-2] += 1
                            if (k, l) in [(1, 2), (2, 1), (2, 3), (3, 2)] and dist[(row+k-2)*W + col+l-2] > v[1]:
                                dist[(row+k-2)*W + col+l-2] = v[1]
                                queue.appendleft(((row+k-2)*W + col+l-2, v[1]))
                            else:
                                queue.append(((row+k-2)*W + col+l-2, v[1]+1))

H, W = map(int, input().split())
C_H, C_W = map(int, input().split())
D_H, D_W = map(int, input().split())

graph = [[] for i in range(H*W)]
S = []
for i in range(H):
    S.append(input())

s = ""
for j in range (W+4):
    s += "#"
S_extended = [s, s]
for i in range(H):
    S_extended.append("##" + S[i] + "##")
S_extended.append(s)
S_extended.append(s)

dist = [infty for i in range(H*W)]
BFS(dist)
if dist[(D_H-1)*W + D_W-1] == infty:
    print("-1")
else:
    print(dist[(D_H-1)*W + D_W-1])

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split()))
si, sj = list(map(lambda x: int(x)-1, input().split()))
ti, tj = list(map(lambda x: int(x)-1, input().split()))
s = [None] * h
for i in range(h):
    s[i] = input()

# 探索時に移動する方向
di = [-1, 0, 1, 0]
dj = [0, -1, 0, 1]

# 距離情報を一番遠い値で初期化
#import numpy as np
INF = int(1e9)
#dist = np.full((h, w), INF)
dist = [[INF for j in range(w)] for i in range(h)]

from collections import deque
q = deque()

# 開始位置
dist[si][sj] = 0
q.append((si,sj))

while (len(q)>0):
    (i, j) = q[0]
    d = dist[i][j]
    q.popleft()
    # 移動Aによるコスト
    for v in range(len(di)):
        ni, nj = i+di[v], j+dj[v]
        if (ni<0 or ni>=h or nj<0 or nj>=w):
            continue # マップの境界
        if (s[ni][nj] == '#'):
            continue # 壁
        if (dist[ni][nj]<=d):
            continue # 探索済みコスト以上
        dist[ni][nj] = d
        q.append((ni, nj))
    # 移動Bによるコスト
    for ei in range(-2, 3):
        for ej in range(-2, 3):
            ni, nj = i+ei, j+ej
            if (ni<0 or ni>=h or nj<0 or nj>=w):
                continue # マップの境界
            if (s[ni][nj] == '#'):
                continue # 壁
            if (dist[ni][nj]<=d):
                continue # 探索済みコスト以上
            dist[ni][nj] = d+1
            q.append((ni, nj))

ans = dist[ti][tj]
if ans == INF:
    ans = -1
print(ans)