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:
# 問題：https://atcoder.jp/contests/abc176/tasks/abc176_d

h, w = map(int, input().strip().split())
cx, cy = map(int, input().strip().split())
dx, dy = map(int, input().strip().split())
cx -= 1
cy -= 1
dx -= 1
dy -= 1
s = [input() for _ in range(h)]
reached = [[] for _ in range(h)]

for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            reached[i].append(0)
        if s[i][j] == '#':
            reached[i].append(1)
res = 0
qx = [cx]
qy = [cy]

while qx:
    pre_qx = []
    pre_qy = []
    while qx:
        x = qx.pop(0)
        y = qy.pop(0)
        if reached[x][y] == 1:
            continue
        pre_qx.append(x)
        pre_qy.append(y)
        reached[x][y] = 1
        if x > 0 and reached[x-1][y] == 0:
            qx.append(x-1)
            qy.append(y)
        if x < h-1 and reached[x+1][y] == 0:
            qx.append(x+1)
            qy.append(y)
        if y > 0 and reached[x][y-1] == 0:
            qx.append(x)
            qy.append(y-1)
        if y < w-1 and reached[x][y+1] == 0:
            qx.append(x)
            qy.append(y+1)
    if reached[dx][dy] == 1:
        break
    res += 1
    while pre_qx:
        x = pre_qx.pop(0)
        y = pre_qy.pop(0)
        lx = max(x-2, 0)
        rx = min(x+3, h)
        ly = max(y-2, 0)
        ry = min(y+3, w)
        for i in range(lx, rx):
            for j in range(ly, ry):
                if reached[i][j] == 0:
                    qx.append(i)
                    qy.append(j)

if reached[dx][dy] == 0:
    res = -1

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, list(input().split()))
Ch, Cw = map(int, list(input().split()))
Ch -= 1
Cw -= 1
Dh, Dw = map(int, list(input().split()))
Dh -= 1
Dw -= 1
S = [list(input()) for _ in range(H)]

dh = [-1, 0, 0, 1]
dw = [0, 1, -1, 0]

INF = pow(10, 10)
seen = [[INF] * W for _ in range(H)]
seen[Ch][Cw] = 0
q = deque()
q.append([Ch, Cw])

while q:
    th, tw = q.pop()
    for i in range(4):
        nh = th + dh[i]
        nw = tw + dw[i]
        if nh < 0 or nh > H - 1 or nw < 0 or nw > W - 1:
            continue
        if S[nh][nw] == '#':
            continue
        if seen[nh][nw] <= seen[th][tw]:
            continue
        seen[nh][nw] = seen[th][tw]
        q.append([nh, nw])
    for dh2 in range(-2, 3):
        for dw2 in range(-2, 3):
            if dh2 == 0 and dw2 == 0:
                continue
            nh = th + dh2
            nw = tw + dw2
            if nh < 0 or nh > H - 1 or nw < 0 or nw > W - 1:
                continue
            if S[nh][nw] == '#':
                continue
            if seen[nh][nw] <= seen[th][tw] + 1:
                continue
            seen[nh][nw] = seen[th][tw] + 1
            q.append([nh, nw])

if seen[Dh][Dw] is INF:
    print(-1)
else:
    print(seen[Dh][Dw])

Submission status: Time Limit Exceeded

Solution code:
import sys

# D - Wizard in Maze
def conv_index(s):
	return int(s) - 1


def search(h, w, set_, mp):
  global Dh
  global Dw
  global can_goal
  global ans

  if h == Dh and w == Dw:
    can_goal = True
    ans.append(mp)
  elif not can_reach(h, w, set_):
    return
  else:
    route = copy.copy(set_)
    route.add(coord(h, w))

    if need_to_use_mp(h, w, route):
      mp += 1

      for i in range(-2, 3):
        search(h - 2, w + i, route, mp)
        search(h + 2, w + i, route, mp)

      for i in range(-2, 3):
        if i != 0:
          search(h - 1, w + i, route, mp)
          search(h + 1, w + i, route, mp)

      search(h, w - 2, route, mp)
      search(h, w + 2, route, mp)
    else:
      search(h - 1, w, route, mp)
      search(h + 1, w, route, mp)
      search(h, w - 1, route, mp)
      search(h, w + 1, route, mp)


def can_reach(h, w, route):
	global H
	global W
	global maze

	if h < 0 or h > H - 1 or w < 0 or w > W - 1:
		return False
	elif maze[h][w] == '#':
		return False
	elif coord(h, w) in route:
		return False
	else:
		return True


def coord(h, w):
  return str(h) + ' ' + str(w)


def need_to_use_mp(h, w, route):
	any_can_reach = False

	if can_reach(h - 1, w, route):
		any_can_reach = True

	if can_reach(h + 1, w, route):
		any_can_reach = True

	if can_reach(h, w - 1, route):
		any_can_reach = True

	if can_reach(h, w + 1, route):
		any_can_reach = True

	if not any_can_reach:
		return True


import copy
sys.setrecursionlimit(1000000)

H, W = map(int, input().split())
Ch, Cw = map(conv_index, input().split())
Dh, Dw = map(conv_index, input().split())

maze = []

for _ in range(H):
	maze.append(input())

can_goal = False
ans = []

search(Ch, Cw, set(), 0)

if not can_goal:
	print(-1)
elif len(ans) == 0:
	print(0)
else:
	print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import sys

# D - Wizard in Maze
def conv_index(s):
	return int(s) - 1


def search(h, w, set_, mp):
  global Dh
  global Dw
  global can_goal
  global ans

  route = copy.copy(set_)

  if h == Dh and w == Dw:
    can_goal = True
    ans.append(mp)
  elif not can_reach(h, w, route):
    return
  else:
    route.add(coord(h, w))

    if need_to_use_mp(h, w, route):
      mp += 1

      for i in range(-2, 3):
        search(h - 2, w + i, route, mp)
        search(h + 2, w + i, route, mp)

      for i in range(-2, 3):
        if i != 0:
          search(h - 1, w + i, route, mp)
          search(h + 1, w + i, route, mp)

      search(h, w - 2, route, mp)
      search(h, w + 2, route, mp)
    else:
      search(h - 1, w, route, mp)
      search(h + 1, w, route, mp)
      search(h, w - 1, route, mp)
      search(h, w + 1, route, mp)


def can_reach(h, w, route):
	global H
	global W
	global maze

	if h < 0 or h > H - 1 or w < 0 or w > W - 1:
		return False
	elif maze[h][w] == '#':
		return False
	elif coord(h, w) in route:
		return False
	else:
		return True


def coord(h, w):
  return str(h) + ' ' + str(w)


def need_to_use_mp(h, w, route):
	any_can_reach = False

	if can_reach(h - 1, w, route):
		any_can_reach = True

	if can_reach(h + 1, w, route):
		any_can_reach = True

	if can_reach(h, w - 1, route):
		any_can_reach = True

	if can_reach(h, w + 1, route):
		any_can_reach = True

	if not any_can_reach:
		return True


import copy
sys.setrecursionlimit(1000000)

H, W = map(int, input().split())
Ch, Cw = map(conv_index, input().split())
Dh, Dw = map(conv_index, input().split())

maze = []

for _ in range(H):
	maze.append(input())

can_goal = False
ans = []

search(Ch, Cw, set(), 0)

if not can_goal:
	print(-1)
elif len(ans) == 0:
	print(0)
else:
	print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
import sys

# D - Wizard in Maze
def conv_index(s):
	return int(s) - 1


def search(h, w, set_, mp):
  global Dh
  global Dw
  global can_goal
  global ans

  route = copy.copy(set_)

  if h == Dh and w == Dw:
    can_goal = True
    ans.append(mp)
  elif not can_reach(h, w, route):
    return
  else:
    route.add(coord(h, w))

    if need_to_use_mp(h, w, route):
      mp += 1

      for i in range(-2, 3):
        search(h - 2, w + i, route, mp)
        search(h + 2, w + i, route, mp)

      for i in range(-2, 3):
        if i != 0:
          search(h - 1, w + i, route, mp)
          search(h + 1, w + i, route, mp)

      search(h, w - 2, route, mp)
      search(h, w + 2, route, mp)
    else:
      search(h - 1, w, route, mp)
      search(h + 1, w, route, mp)
      search(h, w - 1, route, mp)
      search(h, w + 1, route, mp)


def can_reach(h, w, route):
	global H
	global W
	global maze

	if h < 0 or h > H - 1 or w < 0 or w > W - 1:
		return False
	elif maze[h][w] == '#':
		return False
	elif coord(h, w) in route:
		return False
	else:
		return True


def coord(h, w):
  return str(h) + ' ' + str(w)


def need_to_use_mp(h, w, route):
	any_can_reach = False

	if can_reach(h - 1, w, route):
		any_can_reach = True

	if can_reach(h + 1, w, route):
		any_can_reach = True

	if can_reach(h, w - 1, route):
		any_can_reach = True

	if can_reach(h, w + 1, route):
		any_can_reach = True

	if not any_can_reach:
		return True


import copy
sys.setrecursionlimit(1000000)

H, W = map(int, input().split())
Ch, Cw = map(conv_index, input().split())
Dh, Dw = map(conv_index, input().split())

maze = []

for _ in range(H):
	maze.append(input())

can_goal = False
ans = []

search(Ch, Cw, set(), 0)

if not can_goal:
	print(-1)
elif len(ans) == 0:
	print(0)
else:
	print(min(ans))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
from functools import reduce
from queue import Queue
from collections import deque
H, W = list(map(int, input().split(" ")))
current_h, current_w = list(map(int, input().split(" ")))
current_h -= 1
current_w -= 1
goal_h, goal_w = list(map(int, input().split(" ")))
goal_h -= 1
goal_w -= 1

table = [list(input()) for _ in range(H)]

class ZeroOneBFS:

    def __init__(self, table):
        self.table = table
        self.cost_table = []
        for _ in range(H):
            self.cost_table.append([-1 for _ in range(W)])

    def delta(self, h, w):
        res = [(h+1, w),
               (h, w-1), (h, w+1),
               (h-1, w)]
        return res

    def warp(self, h, w):
        res = []
        for dh in range(-2, 3):
            for dw in range(-2, 3):
                if dh == 0 and dw == 0:
                    pass
                else:
                    res.append((h+dh, w+dw))
        return res

    def bfs(self, start_h, start_w):
        dq = deque()
        dq.appendleft((start_h, start_w, 0))
        while dq:
            now_h, now_w, now_c = dq.pop()
            if self.table[now_h][now_w] == "#" or self.cost_table[now_h][now_w] != -1:
                pass
            else:
                self.cost_table[now_h][now_w] = now_c
                for h, w in self.delta(now_h, now_w):
                    if 0 <= h < H and 0 <= w < W and self.table[h][w] != "#":
                        dq.append((h, w, now_c))
                for h, w in self.warp(now_h, now_w):
                    if 0 <= h < H and 0 <= w < W and self.table[h][w] != "#":
                        dq.appendleft((h, w, now_c+1))
        return self.cost_table[goal_h][goal_w]


bfs = ZeroOneBFS(table)
print(bfs.bfs(current_h, current_w))

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
sh, sw = map(int, input().split())
gh, gw = map(int, input().split())

sh += 1
sw += 1
gh += 1
gw += 1
s = sh*3000+sw
g = gh*3000+gw

S = [0]*(H+4)
S[0] = '*'*(W+4)
S[1] = '*'*(W+4)
S[-2] = '*'*(W+4)
S[-1] = '*'*(W+4)
for h in range(2,H+2):
  S[h] = '**' + input() + '**'

visited = [[float('inf')]*(W+4) for _ in range(H+4)]
dh1 = [0,1,0,-1]
dw1 = [1,0,-1,0]
dh2 = [2,2,2,2,2,1,1,1,1,0,0,-1,-1,-1,-1,-2,-2,-2,-2,-2]
dw2 = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
d = []
heapify(d)
heappush(d,s)
ans = float('inf')
while len(d)>0:
  a = heappop(d)
  cnt,a1 = divmod(a,10**7)
  h,w = divmod(a1,3000)
  if cnt>=ans:
    break
  visited[h][w] = cnt
  for i in range(4):
    h1 = h+dh1[i]
    w1 = w+dw1[i]
    if (h1,w1)==(gh,gw):
      ans = cnt
    if S[h1][w1]=='.':
      if visited[h1][w1]>cnt:
        visited[h1][w1]=cnt
        heappush(d,cnt*(10**7)+h1*3000+w1)
  for i in range(20):
    h2 = h+dh2[i]
    w2 = w+dw2[i]
    if (h2,w2)==(gh,gw):
      ans = cnt+1
    if S[h2][w2]=='.':
      if visited[h2][w2]>cnt+1:
        visited[h2][w2]=cnt+1
        heappush(d,(cnt+1)*(10**7)+h2*3000+w2)
ans = ans if ans<float('inf') else -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
sh, sw = map(int, input().split())
gh, gw = map(int, input().split())

sh += 1
sw += 1
gh += 1
gw += 1

S = [0]*(H+4)
S[0] = '*'*(W+4)
S[1] = '*'*(W+4)
S[-2] = '*'*(W+4)
S[-1] = '*'*(W+4)
for h in range(2,H+2):
  S[h] = '**' + input() + '**'

visited = [[float('inf')]*(W+4) for _ in range(H+4)]
dh1 = [0,1,0,-1]
dw1 = [1,0,-1,0]
dh2 = [2,2,2,2,2,1,1,1,1,0,0,-1,-1,-1,-1,-2,-2,-2,-2,-2]
dw2 = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
d = []
heapify(d)
heappush(d,(0,sh,sw))
ans = float('inf')
while len(d)>0:
  cnt,h,w = heappop(d)
  if cnt>=ans:
    break
  if visited[h][w]<=cnt:
    continue
  visited[h][w] = cnt
  for i in range(4):
    h1 = h+dh1[i]
    w1 = w+dw1[i]
    if (h1,w1)==(gh,gw):
      ans = min(ans,cnt)
    if S[h1][w1]=='.':
      if visited[h1][w1]>cnt:
        heappush(d,(cnt,h1,w1))
  for i in range(20):
    h2 = h+dh2[i]
    w2 = w+dw2[i]
    if (h2,w2)==(gh,gw):
      ans = min(ans,cnt+1)
    if S[h2][w2]=='.':
      if visited[h2][w2]>cnt+1:
        heappush(d,(cnt+1,h2,w2))
ans = ans if ans<float('inf') else -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
sh, sw = map(int, input().split())
gh, gw = map(int, input().split())

sh += 1
sw += 1
gh += 1
gw += 1

S = [0]*(H+4)
S[0] = '*'*(W+4)
S[1] = '*'*(W+4)
S[-2] = '*'*(W+4)
S[-1] = '*'*(W+4)
for h in range(2,H+2):
  S[h] = '**' + input() + '**'

visited = [[float('inf')]*(W+4) for _ in range(H+4)]
dh1 = [0,1,0,-1]
dw1 = [1,0,-1,0]
dh2 = [2,2,2,2,2,1,1,1,1,0,0,-1,-1,-1,-1,-2,-2,-2,-2,-2]
dw2 = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
d = []
heapify(d)
heappush(d,(0,sh,sw))
ans = float('inf')
while len(d)>0:
  cnt,h,w = heappop(d)
  if visited[h][w]<=cnt:
    continue
  if cnt>ans:
    break
  visited[h][w] = cnt
  for i in range(4):
    h1 = h+dh1[i]
    w1 = w+dw1[i]
    if (h1,w1)==(gh,gw):
      ans = min(ans,cnt)
    if S[h1][w1]=='.':
      if visited[h1][w1]>cnt:
        heappush(d,(cnt,h1,w1))
  for i in range(20):
    h2 = h+dh2[i]
    w2 = w+dw2[i]
    if (h2,w2)==(gh,gw):
      ans = min(ans,cnt+1)
    if S[h2][w2]=='.':
      if visited[h2][w2]>cnt+1:
        heappush(d,(cnt+1,h2,w2))
ans = ans if ans<float('inf') else -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
sh, sw = map(int, input().split())
gh, gw = map(int, input().split())

sh += 1
sw += 1
gh += 1
gw += 1

S = [0]*(H+4)
S[0] = '*'*(W+4)
S[1] = '*'*(W+4)
S[-2] = '*'*(W+4)
S[-1] = '*'*(W+4)
for h in range(2,H+2):
  S[h] = '**' + input() + '**'

visited = [[float('inf')]*(W+4) for _ in range(H+4)]
dh1 = [0,1,0,-1]
dw1 = [1,0,-1,0]
dh2 = [2,2,2,2,2,1,1,1,1,0,0,-1,-1,-1,-1,-2,-2,-2,-2,-2]
dw2 = [-2,-1,0,1,2,-2,-1,1,2,-2,2,-2,-1,1,2,-2,-1,0,1,2]

from heapq import heappush, heappop, heappushpop, heapify, heapreplace, merge
d = []
heapify(d)
heappush(d,(0,sh,sw))

while len(d)>0:
  cnt,h,w = heappop(d)
  if visited[h][w]<=cnt:
    continue
  visited[h][w] = cnt
  for i in range(4):
    h1 = h+dh1[i]
    w1 = w+dw1[i]
    if S[h1][w1]=='.':
      if visited[h1][w1]>cnt:
        heappush(d,(cnt,h1,w1))
  for i in range(20):
    h2 = h+dh2[i]
    w2 = w+dw2[i]
    if S[h2][w2]=='.':
      if visited[h2][w2]>cnt+1:
        heappush(d,(cnt+1,h2,w2))
ans = visited[gh][gw] if visited[gh][gw]<float('inf') else -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
INF=1001001001
dy=[0,1,0,-1]
dx=[1,0,-1,0]
my=[-2,-2,-2,-2,-2,-1,-1,-1,-1,0,0,1,1,1,1,2,2,2,2,2]
mx=[2,1,0,-1,-2,2,1,-1,-2,2,-2,2,1,-1,-2,2,1,0,-1,-2]
h,w=map(int,input().split())
ch,cw=map(int,input().split())
ch-=1
cw-=1
dh,dw=map(int,input().split())
dh-=1
dw-=1
s=[list(input()) for i in range(h)]
dist=[[INF for i in range(w)] for j in range(h)]
dist[ch][cw]=0
d=deque([])
d.append([ch,cw])

while d:
  nowh,noww=d.popleft()
  for i in range(4):
    th=nowh+dy[i]
    tw=noww+dx[i]
    if 0<=th<=h-1 and 0<=tw<=w-1 and dist[th][tw]>dist[nowh][noww] and s[th][tw]==".":
      d.appendleft([th,tw])
      dist[th][tw]=dist[nowh][noww]
  for i in range(20):
    th=nowh+my[i]
    tw=noww+mx[i]
    if 0<=th<=h-1 and 0<=tw<=w-1 and dist[th][tw]>dist[nowh][noww]+1 and s[th][tw]==".":
      d.append([th,tw])
      dist[th][tw]=dist[nowh][noww]+1

ans=dist[dh][dw]
if ans==INF:
  ans=-1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#input
h, w = map(int, input().split())
c_h, c_w = map(int, input().split())
d_h, d_w = map(int, input().split())
s = [input() for _ in range(h)]

#output
from collections import deque

INF = pow(10, 10)
dp = [[INF] * w for _ in range(h)]

trans_a = [(0, 1), (1, 0), (0, -1), (-1, 0)]
trans_b = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + trans_a]

q = deque([])
q.append((c_h-1, c_w-1))
dp[c_h-1][c_w-1] = 0

while q:
    x, y = q.popleft()

    for dx, dy in trans_a:
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and dp[nx][ny] > dp[x][y]:
            q.appendleft((nx, ny))#ここを変更
            dp[nx][ny] = dp[x][y]#ここを変更

    for dx, dy in trans_b:
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and dp[nx][ny] > dp[x][y]:
            q.append((nx, ny))
            dp[nx][ny] = dp[x][y] + 1

answer = dp[d_h-1][d_w-1]

# %%
if answer == INF:
    print(-1)
else:
    print(answer)

Submission status: Time Limit Exceeded

Solution code:
#input
h, w = map(int, input().split())
c_h, c_w = map(int, input().split())
d_h, d_w = map(int, input().split())
s = [input() for _ in range(h)]

#output
from collections import deque

INF = pow(10, 10)
dp = [[INF] * w for _ in range(h)]

trans_a = [(0, 1), (1, 0), (0, -1), (-1, 0)]
trans_b = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + trans_a]

q = deque([])
q.append((c_h-1, c_w-1))
dp[c_h-1][c_w-1] = 0

while q:
    x, y = q.popleft()

    for dx, dy in trans_a:
        nx, ny = x + dx, y + dy
        if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and dp[nx][ny] > dp[x][y]:
            q.appendleft((nx, ny))#ここを変更
            dp[nx][ny] = dp[x][y]#ここを変更

    for dxb, dyb in trans_b:
        nx2, ny2 = x + dxb, y + dyb
        if 0 <= nx2 < h and 0 <= ny2 < w and s[nx2][ny2] != "#" and dp[nx2][ny2] > dp[x][y]:
            q.append((nx2, ny2))
            dp[nx2][ny2] = dp[x][y] + 1

answer = dp[d_h-1][d_w-1]

# %%
if answer == INF:
    print(-1)
else:
    print(answer)

Submission status: Time Limit Exceeded

Solution code:
#atcoder template
def main():
    import sys
    imput = sys.stdin.readline
    #文字列入力の時は上記はerrorとなる。
    #ここにコード
    #input
    h, w = map(int, input().split())
    c_h, c_w = map(int, input().split())
    d_h, d_w = map(int, input().split())
    s = [input() for _ in range(h)]

    #output
    from collections import deque

    INF = pow(10, 10)
    dp = [[INF] * w for _ in range(h)]

    trans_a = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    trans_b = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + trans_a]

    q = deque([])
    q.append((c_h-1, c_w-1))
    dp[c_h-1][c_w-1] = 0

    while q:
        x, y = q.popleft()

        for dx, dy in trans_a:
            nx, ny = x + dx, y + dy
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and dp[nx][ny] > dp[x][y]:
                q.appendleft((nx, ny))#ここを変更
                dp[nx][ny] = dp[x][y]#ここを変更

        for dxb, dyb in trans_b:
            nx2, ny2 = x + dxb, y + dyb
            if 0 <= nx2 < h and 0 <= ny2 < w and s[nx2][ny2] != "#" and dp[nx2][ny2] > dp[x][y]:
                q.append((nx2, ny2))
                dp[nx2][ny2] = dp[x][y] + 1

    answer = dp[d_h-1][d_w-1]

    # %%
    if answer == INF:
        print(-1)
    else:
        print(answer)

    #N = 1のときなどcorner caseを確認！
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#atcoder template
def main():
    import sys
    imput = sys.stdin.readline
    #文字列入力の時は上記はerrorとなる。
    #ここにコード
    #input
    h, w = map(int, input().split())
    c_h, c_w = map(int, input().split())
    d_h, d_w = map(int, input().split())
    s = [input() for _ in range(h)]

    #output
    from collections import deque
    import numpy as np

    INF = pow(10, 10)
    dp = np.full((h, w), INF)
    #dp = [[INF] * w for _ in range(h)]

    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    dxb = [-2, -2, -2, -2, -2, -1, -1, -1, -1, 0, 0, 1, 1,  1, 1, 2, 2, 2, 2, 2]
    dyb = [-2, -1, 0,   1,  2, -2, -1,  1,  2,-2, 2, -2,-1, 1, 2, -2,-1,0, 1, 2]

    q = deque([])
    q.append((c_h-1, c_w-1))
    dp[c_h-1, c_w-1] = 0

    while q:
        x, y = q.popleft()

        if x == d_h-1 and y == d_w-1:
            break

        for i in range(0, 4):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and dp[nx, ny] > dp[x, y]:
                q.appendleft((nx, ny))#ここを変更
                dp[nx, ny] = dp[x, y]#ここを変更

        for j in range(0, 20):
            nx2, ny2 = x + dxb[j], y + dyb[j]
            if 0 <= nx2 < h and 0 <= ny2 < w and s[nx2][ny2] != "#" and dp[nx2, ny2] > dp[x, y]:
                q.append((nx2, ny2))
                dp[nx2, ny2] = dp[x, y] + 1

    """def clear_maze(sx, sy, gx, gy, maze):
        def bfs():
            q = deque([])
            q.append((sx, sy))
            dp[sx][sy] = 0

            while len(q):
                x, y = q.popleft()

                if x == gx and y == gy:
                    break

                for i in range(0, 4):
                    nx, ny = x + dx[i], y + dy[i]
                    if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and dp[nx][ny] > dp[x][y]:
                        q.appendleft((nx, ny))#ここを変更
                        dp[nx][ny] = dp[x][y]#ここを変更

                for j in range(0, 20):
                    nx2, ny2 = x + dxb[j], y + dyb[j]
                    if 0 <= nx2 < h and 0 <= ny2 < w and maze[nx2][ny2] != "#" and dp[nx2][ny2] > dp[x][y]:
                        q.append((nx2, ny2))
                        dp[nx2][ny2] = dp[x][y] + 1 
            return dp[gx][gy]
        return bfs()"""

    answer = dp[d_h-1, d_w-1]

    # %%
    if answer == INF:
        print(-1)
    else:
        print(answer)

    #N = 1のときなどcorner caseを確認！
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs():
    move=[[1,0],[0,1],[-1,0],[0,-1]]
    
    queue=deque()

    queue.append((0,(sy,sx))) #queue=deque([[sy,sx]])でもよい
    visited[sy][sx]=0 #スタート地点の距離は0
    while queue:
        cnt,(y,x)=queue.popleft()
        
        
        for dy,dx in move:
            my,mx=y+dy,x+dx 
            if my<0 or my>=tate:
                continue
            if mx<0 or mx>=yoko:
                continue
            if maze[my][mx]=="#":
                continue
            if visited[my][mx]>cnt:
                queue.append((cnt,(my,mx)))
                visited[my][mx]=cnt # visitedは距離も兼ねてる
        for my in range(y-2,y+3):
            for mx in range(x-2,x+3):
                if my<0 or my>=tate:
                    continue
                if mx<0 or mx>=yoko:
                    continue
                if maze[my][mx]=="#":
                    continue
                if visited[my][mx]>cnt+1:
                    queue.append((cnt+1,(my,mx)))
                    visited[my][mx]=cnt+1
    if visited[gy][gx]==inf:
        print(-1)
    else:
        print(visited[gy][gx])


tate,yoko=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
sy,sx,gy,gx=sy-1,sx-1,gy-1,gx-1
maze=[]
inf=float('inf')
visited=[[inf]*yoko for i in range(tate)]

for i in range(tate):
    line=list(input())
    maze.append(line)
bfs()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs():
    move=[[1,0],[0,1],[-1,0],[0,-1]]
    
    queue=deque()
    queue.append([sy,sx]) #queue=deque([[sy,sx]])でもよい
    visited[sy][sx]=0 #スタート地点の距離は0
    while queue:
        y,x=queue.popleft()
        cnt=visited[y][x]
        
        for dy,dx in move:
            my,mx=y+dy,x+dx 
            if my<0 or my>=tate:
                continue
            if mx<0 or mx>=yoko:
                continue
            if maze[my][mx]=="#":
                continue
            if visited[my][mx]>cnt:
                queue.append([my,mx])
                visited[my][mx]=cnt # visitedは距離も兼ねてる
        for my in range(y-2,y+3):
            for mx in range(x-2,x+3):
                if my<0 or my>=tate:
                    continue
                if mx<0 or mx>=yoko:
                    continue
                if maze[my][mx]=="#":
                    continue
                if visited[my][mx]>cnt+1:
                    queue.append([my,mx])
                    visited[my][mx]=cnt+1
    if visited[gy][gx]==inf:
        print(-1)
    else:
        print(visited[gy][gx])


tate,yoko=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
sy,sx,gy,gx=sy-1,sx-1,gy-1,gx-1
maze=[]
inf=float('inf')
visited=[[inf]*yoko for i in range(tate)]

for i in range(tate):
    line=list(input())
    maze.append(line)
bfs()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs():
    move=[[1,0],[0,1],[-1,0],[0,-1]]
    
    queue=deque()
    queue.append([sy,sx]) #queue=deque([[sy,sx]])でもよい
    visited[sy][sx]=0 #スタート地点の距離は0
    while queue:
        y,x=queue.popleft()
        cnt=visited[y][x]
        
        for dy,dx in move:
            my,mx=y+dy,x+dx 
            if not(0<=my<tate and 0<=mx<yoko):
                continue
            if maze[my][mx]=="#":
                continue
            if visited[my][mx]>cnt:
                queue.append([my,mx])
                visited[my][mx]=cnt # visitedは距離も兼ねてる
        for my in range(y-2,y+3):
            for mx in range(x-2,x+3):
                if not(0<=my<tate and 0<=mx<yoko):
                    continue
                if maze[my][mx]=="#":
                    continue
                if visited[my][mx]>cnt+1:
                    queue.append([my,mx])
                    visited[my][mx]=cnt+1
    if visited[gy][gx]==inf:
        print(-1)
    else:
        print(visited[gy][gx])


tate,yoko=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
sy,sx,gy,gx=sy-1,sx-1,gy-1,gx-1
maze=[]
inf=float('inf')
visited=[[inf]*yoko for i in range(tate)]

for i in range(tate):
    line=list(input())
    maze.append(line)
bfs()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs():
    move=[[1,0],[0,1],[-1,0],[0,-1]]
    
    queue=deque()
    queue.append([sy,sx]) #queue=deque([[sy,sx]])でもよい
    visited[sy][sx]=0 #スタート地点の距離は0
    while queue:
        y,x=queue.popleft()
        cnt=visited[y][x]
        
        for dy,dx in move:
            my,mx=y+dy,x+dx 
            if (0<=my<tate and 0<=mx<yoko) and maze[my][mx]=="." and visited[my][mx]>cnt:
                queue.append([my,mx])
                visited[my][mx]=cnt # visitedは距離も兼ねてる
        for my in range(y-2,y+3):
            for mx in range(x-2,x+3):
                if (0<=my<tate and 0<=mx<yoko) and maze[my][mx]==".":
                    if visited[my][mx]>cnt+1:
                        queue.append([my,mx])
                        visited[my][mx]=cnt+1
    if visited[gy][gx]==inf:
        print(-1)
    else:
        print(visited[gy][gx])


tate,yoko=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
sy,sx,gy,gx=sy-1,sx-1,gy-1,gx-1
maze=[]
inf=float('inf')
visited=[[inf]*yoko for i in range(tate)]

for i in range(tate):
    line=list(input())
    maze.append(line)
bfs()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
def bfs():
    move=[[1,0],[0,1],[-1,0],[0,-1]]
    
    queue=deque()
    queue.append([sy,sx]) #queue=deque([[sy,sx]])でもよい
    visited[sy][sx]=0 #スタート地点の距離は0
    while queue:
        y,x=queue.popleft()
        cnt=visited[y][x]
        
        for dy,dx in move:
            my,mx=y+dy,x+dx 
            if (0<=my<tate and 0<=mx<yoko) and maze[my][mx]=="." and visited[my][mx]>cnt:
                queue.append([my,mx])
                visited[my][mx]=cnt # visitedは距離も兼ねてる
        for my in range(y-2,y+3):
            for mx in range(x-2,x+3):
                if (0<=my<tate and 0<=mx<yoko) and maze[my][mx]==".":
                    if visited[my][mx]>cnt+1:
                        queue.append([my,mx])
                        visited[my][mx]=cnt+1
    if visited[gy][gx]==inf:
        print(-1)
    else:
        print(visited[gy][gx])


tate,yoko=map(int,input().split())
sy,sx=map(int,input().split())
gy,gx=map(int,input().split())
sy,sx,gy,gx=sy-1,sx-1,gy-1,gx-1
maze=[]
inf=float('inf')
visited=[[inf]*yoko for i in range(tate)]

for i in range(tate):
    line=list(input())
    maze.append(line)
bfs()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.buffer.readline

H, W = list(map(int, readline().split()))
CH, CW = list(map(int, readline().split()))
DH, DW = list(map(int, readline().split()))
S = []
for _ in range(H):
    S.append(list(input()))

# 1-index -> 0-index
CH -= 1
CW -= 1
DH -= 1
DW -= 1

from collections import deque
seen = set()
queue = deque([(0, CH, CW)])
offsets = [(-1, 0), (1, 0), (0, -1), (0, 1)]

while queue:
    move, row, col = queue.popleft()

    # print(row, col, queue)

    if (row, col) in seen:
        continue

    if row == DH and col == DW:
        print(move)
        sys.exit(0)

    seen.add((row, col))

    for r_offset, c_offset in offsets:
        new_row = row + r_offset
        new_col = col + c_offset
        if 0 <= new_row < H and 0 <= new_col < W and S[new_row][new_col] == '.' and (new_row, new_col) not in seen:
            queue.appendleft((move, new_row, new_col))


    for i in range(-2, 3):
        for j in range(-2, 3):
            new_row = row + i
            new_col = col + j

            if 0 <= new_row < H and 0 <= new_col < W and S[new_row][new_col] == '.' and (new_row, new_col) not in seen:
                queue.append((move+1, new_row, new_col))

print(-1)