Problem:


Score : 400 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

1

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

Note that he cannot walk diagonally.

Sample Input 2

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

Sample Output 2

-1

He cannot move from there.

Sample Input 3

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

Sample Output 3

0

No use of magic is needed.

Sample Input 4

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

Sample Output 4

2



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


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest
from collections import deque

def resolve():
    readline=sys.stdin.readline

    h,w=map(int, readline().rstrip().split())
    ch,cw=map(int, readline().rstrip().split())
    dh,dw=map(int, readline().rstrip().split())
    ch-=1
    cw-=1
    dh-=1
    dw-=1

    mp=[[None for i in range(w)] for j in range(h)]

    for i in range(h):
        ss = readline().rstrip()
        for j in range(w):
            if ss[j]=="#":
                mp[i][j] = -1

    d = deque()
    d2 = deque()

    if mp[ch][cw]==None:
        mp[ch][cw]=0
        d.append((ch,cw))
    while len(d) > 0:
        y,x = d.popleft()
        d2.append((y,x))
        for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
            ny=y+dy
            nx=x+dx
            if 0 <= ny < h and 0 <= nx < w and mp[ny][nx]==None:
                mp[ny][nx]=mp[y][x]
                d.append((ny,nx))
        if len(d)==0:
            while len(d2) > 0:
                y2,x2 = d2.popleft()
                for dy in range(-2,3):
                    for dx in range(-2,3):
                        ny=y2+dy
                        nx=x2+dx
                        if 0 <= ny < h and 0 <= nx < w and mp[ny][nx]==None:
                            mp[ny][nx]=mp[y][x]+1
                            d.append((ny,nx))
    if mp[dh][dw] == None:
        print(-1)
    else:
        print(mp[dh][dw])    
    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
from itertools import count


def _dijkstra(G, source, weight, pred=None, paths=None, cutoff=None, target=None):
    return _dijkstra_multisource(
        G, [source], weight, pred=pred, paths=paths, cutoff=cutoff, target=target
    )


def _dijkstra_multisource(
    G, sources, weight, pred=None, paths=None, cutoff=None, target=None):
    G_succ = G._succ if G.is_directed() else G._adj

    push = heappush
    pop = heappop
    dist = {}  # dictionary of final distances
    seen = {}
    # fringe is heapq with 3-tuples (distance,c,node)
    # use the count c to avoid comparing nodes (may not be able to)
    c = count()
    fringe = []
    for source in sources:
        if source not in G:
            raise KeyError
        seen[source] = 0
        push(fringe, (0, next(c), source))
    while fringe:
        (d, _, v) = pop(fringe)
        if v in dist:
            continue  # already searched this node.
        dist[v] = d
        if v == target:
            break
        for u, e in G_succ[v].items():
            cost = weight(v, u, e)
            if cost is None:
                continue
            vu_dist = dist[v] + cost
            if cutoff is not None:
                if vu_dist > cutoff:
                    continue
            if u in dist:
                u_dist = dist[u]
                if vu_dist < u_dist:
                    raise ValueError("Contradictory paths found:", "negative weights?")
                elif pred is not None and vu_dist == u_dist:
                    pred[u].append(v)
            elif u not in seen or vu_dist < seen[u]:
                seen[u] = vu_dist
                push(fringe, (vu_dist, next(c), u))
                if paths is not None:
                    paths[u] = paths[v] + [u]
                if pred is not None:
                    pred[u] = [v]
            elif vu_dist == seen[u]:
                if pred is not None:
                    pred[u].append(v)
    return dist


def dijkstra_path_length(G, source, target, weight="weight"):
    
    if source == target:
        return 0
    weight = _weight_function(G, weight)
    length = _dijkstra(G, source, weight, target=target)
    try:
        return length[target]
    except KeyError:
        raise KeyError


def _weight_function(G, weight):
    if callable(weight):
        return weight
    if G.is_multigraph():
        return lambda u, v, d: min(attr.get(weight, 1) for attr in d.values())
    return lambda u, v, data: data.get(weight, 1)


class Graph:
    node_dict_factory = dict
    node_attr_dict_factory = dict
    adjlist_outer_dict_factory = dict
    adjlist_inner_dict_factory = dict
    edge_attr_dict_factory = dict
    graph_attr_dict_factory = dict
    
    def __init__(self, incoming_graph_data=None, **attr):
        
        self.graph_attr_dict_factory = self.graph_attr_dict_factory
        self.node_dict_factory = self.node_dict_factory
        self.node_attr_dict_factory = self.node_attr_dict_factory
        self.adjlist_outer_dict_factory = self.adjlist_outer_dict_factory
        self.adjlist_inner_dict_factory = self.adjlist_inner_dict_factory
        self.edge_attr_dict_factory = self.edge_attr_dict_factory

        self.graph = self.graph_attr_dict_factory()  # dictionary for graph attributes
        self._node = self.node_dict_factory()  # empty node attribute dict
        self._adj = self.adjlist_outer_dict_factory()  # empty adjacency dict
        # load graph attributes (must be after convert)
        self.graph.update(attr)

    def add_edge(self, u_of_edge, v_of_edge, **attr):
        
        u, v = u_of_edge, v_of_edge
        # add nodes
        if u not in self._node:
            self._adj[u] = self.adjlist_inner_dict_factory()
            self._node[u] = self.node_attr_dict_factory()
        if v not in self._node:
            self._adj[v] = self.adjlist_inner_dict_factory()
            self._node[v] = self.node_attr_dict_factory()
        # add the edge
        datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
        datadict.update(attr)
        self._adj[u][v] = datadict
        self._adj[v][u] = datadict

    def is_multigraph(self):
        """Returns True if graph is a multigraph, False otherwise."""
        return False

    def is_directed(self):
        """Returns True if graph is directed, False otherwise."""
        return False

    def __iter__(self):
        """Iterate over the nodes. Use: 'for n in G'.
        Returns
        -------
        niter : iterator
            An iterator over all nodes in the graph.
        Examples
        --------
        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> [n for n in G]
        [0, 1, 2, 3]
        >>> list(G)
        [0, 1, 2, 3]
        """
        return iter(self._node)



def is_inside(x, y, W, H, G):
    return (x <= H-1 and y <= W-1 and
            x >= 0 and y >= 0 and
            G[x][y] != "#")


def main():
    graph = Graph()
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    G = [list(input()) for _ in range(H)]
    seen = set()

    for h in range(H):
        for w in range(W):
            v = h * W + w
            if not is_inside(h, w, W, H, G):
                continue
            for step_h in range(-2, 3):
                for step_w in range(-2, 3):
                    h_, w_ = h+step_h, w+step_w
                    v_ = h_ * W + w_
                    if is_inside(h_, w_, W, H, G) and v_ not in seen:
                        if ((max(abs(step_h), abs(step_w)) == 1) and
                                (min(abs(step_h), abs(step_w)) == 0)):
                            graph.add_edge(v, v_, weight=0)

                        else:
                            graph.add_edge(v, v_, weight=1)
            seen.add(v)
    
    start = (Ch - 1) * W + (Cw - 1)
    end = (Dh - 1) * W + (Dw - 1)
    try:
        ans = dijkstra_path_length(graph, start, end)
    except:
        ans = -1

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
import numpy as np

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

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

Submission status: Time Limit Exceeded

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest
from collections import deque

def resolve():
    readline=sys.stdin.readline

    h,w=map(int, readline().rstrip().split())
    ch,cw=map(int, readline().rstrip().split())
    dh,dw=map(int, readline().rstrip().split())
    ch-=1
    cw-=1
    dh-=1
    dw-=1

    mp=[[None for i in range(w)] for j in range(h)]

    for i in range(h):
        ss = readline().rstrip()
        for j in range(w):
            if ss[j]=="#":
                mp[i][j] = -1

    d = deque()

    if mp[ch][cw]==None:
        mp[ch][cw]=0
        d.append((ch,cw))

    wrps=set()
    while len(d) > 0:
        y,x = d.popleft()
        for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
            ny=y+dy
            nx=x+dx
            if 0 <= ny < h and 0 <= nx < w and mp[ny][nx]==None:
                mp[ny][nx]=mp[y][x]
                d.append((ny,nx))
        for dy in range(-2,3):
            for dx in range(-2,3):
                ny=y+dy
                nx=x+dx
                if 0 <= ny < h and 0 <= nx < w:
                    wrps.add((ny,nx))
        if len(d)==0:
            for ny,nx in wrps:
                if mp[ny][nx]==None:
                    mp[ny][nx]=mp[y][x]+1
                    d.append((ny,nx))
            wrps=set()
    if mp[dh][dw] == None:
        print(-1)
    else:
        print(mp[dh][dw])    
    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
import numpy as np

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

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

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx


def is_inside(x, y, W, H, G):
    return (x <= H-1 and y <= W-1 and
            x >= 0 and y >= 0 and
            G[x][y] != "#")


def main():
    graph = nx.Graph()
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    G = [list(input()) for _ in range(H)]
    seen = set()

    for h in range(H):
        for w in range(W):
            v = h * W + w
            if not is_inside(h, w, W, H, G):
                continue
            for step_h in range(-2, 3):
                for step_w in range(-2, 3):
                    h_, w_ = h+step_h, w+step_w
                    v_ = h_ * W + w_
                    if is_inside(h_, w_, W, H, G) and v_ not in seen:
                        if ((max(abs(step_h), abs(step_w)) == 1) and
                                (min(abs(step_h), abs(step_w)) == 0)):
                            graph.add_edge(v, v_, weight=0)

                        else:
                            graph.add_edge(v, v_, weight=1)
            seen.add(v)
    
    start = (Ch - 1) * W + (Cw - 1)
    end = (Dh - 1) * W + (Dw - 1)
    try:
        ans = nx.dijkstra_path_length(graph, start, end)
    except nx.NetworkXNoPath:
        ans = -1

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import networkx as nx


def is_inside(x, y, W, H, G):
    return (x <= H-1 and y <= W-1 and
            x >= 0 and y >= 0 and
            G[x][y] != "#")


def main():
    graph = nx.Graph()
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    G = [list(input()) for _ in range(H)]

    for h in range(H):
        for w in range(W):
            if not is_inside(h, w, W, H, G):
                continue

            v = h * W + w
            for step_h in range(-2, 3):
                for step_w in range(-2, 3):
                    h_, w_ = h+step_h, w+step_w
                    v_ = h_ * W + w_
                    if is_inside(h_, w_, W, H, G):
                        if ((max(abs(step_h), abs(step_w)) == 1) and
                                (min(abs(step_h), abs(step_w)) == 0)):
                            graph.add_edge(v, v_, weight=0)

                        else:
                            graph.add_edge(v, v_, weight=1)
    start = (Ch - 1) * W + (Cw - 1)
    end = (Dh - 1) * W + (Dw - 1)
    try:
        ans = nx.dijkstra_path_length(graph, start, end)
    except nx.NetworkXNoPath:
        ans = -1

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

di = [-1,0,1,0]
dj = [0,-1,0,1]

H,W = map(int, input().split())
si,sj = map(int, input().split())
ti,tj = map(int, input().split())
si -= 1
sj -= 1
ti -= 1
tj -= 1
inf = 10**9
s = list()
for i in range(H):
  s.append(input())

dist = [[inf]*W for i in range(H)]
q = deque()
dist[si][sj] = 0
q.append([si,sj])

while len(q) > 0:
  tmp = q.popleft()
  i = tmp[0]
  j = tmp[1]
  d = dist[i][j]
  if dist[i][j] != d:
    continue
  for v in range(4):
    ni = i + di[v]
    nj = 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])
  
  for ei in range(-2,3,1):
    for ej in range(-2,3,1):
      ni = i+ei
      nj = 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+1:
        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:
import sys
import re
import queue
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def isIn(H,W,x,y):
	if 0<= x and x <= H-1 and 0<=y and y<=W-1:
		return True
	else:
		return False

def main():
	H,W = i_map()

	C_h,C_w = i_map()
	D_h,D_w = i_map()

	S = []
	for i in range(0,H):
		tmp = s_input()
		tmp2 = []
		for j in range(0,W):
			tmp2.append(tmp[j])
		S.append(tmp2)

	start = [C_h-1,C_w-1]
	exit = [D_h-1,D_w-1]

	rel_matrix = [([[] for i in range(W)]) for i in range(H)]
	dir = [[-1,0],[1,0],[0,-1],[0,1]]
	for i in range(0,H):
		for j in range(0,W):
			for v_dir in dir:
				if isIn(H,W,i+v_dir[0],j+v_dir[1]):
					if(S[i][j] == '.' and S[i+v_dir[0]][j+v_dir[1]] == '.'):
						rel_matrix[i][j].append((i+v_dir[0],j+v_dir[1]))

	color = [['white' for i in range(W)] for j in range(H)]
	cost = [[-1 for i in range(W)] for j in range(H)]
	
	q =  queue.Queue()
	cost[start[0]][start[1]] = 0
	color[start[0]][start[1]]='gray'
	q.put(start)
	while(not q.empty()):
		u = q.get()
		for rel in rel_matrix[u[0]][u[1]]:
			if color[rel[0]][rel[1]] == 'white':
				cost[rel[0]][rel[1]] = 0
				color[rel[0]][rel[1]]  = 'gray'
				q.put(rel)
		color[u[0]][u[1]] = 'black'

	current_cost = 0
	while True:
		currentList = []
		for i in range(0,H):
			for j in range(0,W):
				if(cost[i][j] == current_cost):
					currentList.append((i,j))
		if(len(currentList)==0):
			break

		nextList  = []
		for kouho in currentList:
			for i in range(-2,3):
				for j in range(-2,3):
					if(kouho[0]+i >= 0 and kouho[0]+i <= H-1 and kouho[1] + j >= 0 and kouho[1] + j <= W-1):
						if(S[kouho[0]+i][kouho[1]+j]=='.' and color[kouho[0]+i][kouho[1]+j] == 'white'):
							nextList.append((kouho[0]+i,kouho[1]+j))
		nextList = set(nextList)
		for next in nextList:
			if(color[next[0]][next[1]]=='white'):
				q2 = queue.Queue()
				cost[next[0]][next[1]] =current_cost+1
				color[next[0]][next[1]] = 'gray'
				q2.put(next)
				while(not q2.empty()):
					u = q2.get()
					for rel in rel_matrix[u[0]][u[1]]:
						if color[rel[0]][rel[1]] == 'white':
							cost[rel[0]][rel[1]] = current_cost+1
							color[rel[0]][rel[1]]  = 'gray'
							q2.put(rel)
					color[u[0]][u[1]] = 'black'
		current_cost += 1


	print(cost[D_h-1][D_w-1])



if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import collections

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [input() for _ in range(H)]
INF = 10**10
cost = [[INF] * W for _ in range(H)]
cost[Ch - 1][Cw - 1] = 0
walk = [(-1, 0), (0, 1), (0, -1), (1, 0)]
warp = [(-2, 2), (-2, 1), (-2, 0), (-2, -1), (-2, -2), (-1, 2), (-1, 1), (-1, -1), (-1, -2), (0, 2), (0, -2), (1, 2), (1, 1), (1, -1), (1, -2), (2, 2), (2, 1), (2, 0), (2, -1), (2, -2)]

q = collections.deque([[Ch - 1, Cw - 1, 0]])
while q:
  h, w, c = q.popleft()
  
  for wk in walk:
    dh, dw = wk
    nh = h + dh
    nw = w + dw
  
    if 0 <= nh <= H - 1 and 0 <= nw <= W - 1 and maze[nh][nw] == "." and c < cost[nh][nw]:
      cost[nh][nw] = c
      q.appendleft([nh, nw, c])

  for wp in warp:
    dh, dw = wp
    nh = h + dh
    nw = w + dw
  
    if 0 <= nh <= H - 1 and 0 <= nw <= W - 1 and maze[nh][nw] == "." and c + 1 < cost[nh][nw]:
      cost[nh][nw] = c + 1
      q.append([nh, nw, c + 1])

print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
import collections

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [input() for _ in range(H)]
INF = 10**10
cost = [[INF] * W for _ in range(H)]

q = collections.deque([[Ch - 1,Cw - 1, 0]])
while len(q) > 0:
  h, w, c = q.popleft()
  
  if 0 <= h <= H - 1 and 0 <= w <= W - 1 and maze[h][w] == "." and c + 1 < cost[h][w]:
    cost[h][w] = c
    q.appendleft([h + 1, w    , c])
    q.appendleft([h - 1, w    , c])
    q.appendleft([h    , w + 1, c])
    q.appendleft([h    , w - 1, c])
    
    q.append([h - 2, w + 2, c + 1])
    q.append([h - 2, w + 1, c + 1])
    q.append([h - 2, w    , c + 1])
    q.append([h - 2, w - 1, c + 1])
    q.append([h - 2, w - 2, c + 1])
    q.append([h - 1, w + 2, c + 1])
    q.append([h - 1, w + 1, c + 1])
    q.append([h - 1, w - 1, c + 1])
    q.append([h - 1, w - 2, c + 1])
    q.append([h    , w + 2, c + 1])
    q.append([h    , w - 2, c + 1])
    q.append([h + 1, w + 2, c + 1])
    q.append([h + 1, w + 1, c + 1])
    q.append([h + 1, w - 1, c + 1])
    q.append([h + 1, w - 2, c + 1])
    q.append([h + 2, w + 2, c + 1])
    q.append([h + 2, w + 1, c + 1])
    q.append([h + 2, w    , c + 1])
    q.append([h + 2, w - 1, c + 1])
    q.append([h + 2, w - 2, c + 1])
print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
import collections

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [input() for _ in range(H)]
INF = 10**10
cost = [[INF] * W for _ in range(H)]

q = collections.deque([[Ch - 1,Cw - 1, 0]])
while len(q) > 0:
  h, w, c = q.popleft()
  
  if 0 <= h <= H - 1 and 0 <= w <= W - 1 and maze[h][w] == "." and c < cost[h][w]:
    cost[h][w] = c
    q.appendleft([h + 1, w    , c])
    q.appendleft([h - 1, w    , c])
    q.appendleft([h    , w + 1, c])
    q.appendleft([h    , w - 1, c])
    
    q.append([h - 2, w + 2, c + 1])
    q.append([h - 2, w + 1, c + 1])
    q.append([h - 2, w    , c + 1])
    q.append([h - 2, w - 1, c + 1])
    q.append([h - 2, w - 2, c + 1])
    q.append([h - 1, w + 2, c + 1])
    q.append([h - 1, w + 1, c + 1])
    q.append([h - 1, w - 1, c + 1])
    q.append([h - 1, w - 2, c + 1])
    q.append([h    , w + 2, c + 1])
    q.append([h    , w - 2, c + 1])
    q.append([h + 1, w + 2, c + 1])
    q.append([h + 1, w + 1, c + 1])
    q.append([h + 1, w - 1, c + 1])
    q.append([h + 1, w - 2, c + 1])
    q.append([h + 2, w + 2, c + 1])
    q.append([h + 2, w + 1, c + 1])
    q.append([h + 2, w    , c + 1])
    q.append([h + 2, w - 1, c + 1])
    q.append([h + 2, w - 2, c + 1])
print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int,input().split())
ch, cw = map(int,input().split())
Dh, Dw = map(int,input().split())

M = ['##' + input() + '##' for _ in range(h)]
for i in range(2):
    M.insert(0,'#'*(w+4))
    M.append('#'*(w+4))

INF = float('inf')
cost = [[INF for _ in range(w+4)] for _ in range(h+4)]
cost0 = deque()
ans = -1

cost0.append((ch+1, cw+1, 0))
cost[ch+1][cw+1] = 0

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

cost1 = deque()

while cost0:
    h, w, c = cost0.popleft()
    cost1.append((h, w, c))
    
    for i,j in move:
        dh = h + i
        dw = w + j
        if M[dh][dw] == '.' and c < cost[dh][dw]: #コストが高いところから低いところに戻らないようにするため
            cost[dh][dw] = c
            cost0.appendleft((dh, dw, cost[dh][dw]))
    
    if len(cost0) == 0:
        while cost1:
            h, w, c = cost1.popleft()
            for i,j in warp:
                dh = h + i
                dw = w + j
                if M[dh][dw] == '.' and c+1 < cost[dh][dw]:  #無駄なワープをなくすため
                    cost[dh][dw] = c+1
                    cost0.append((dh, dw, cost[dh][dw]))
    if cost[Dh+1][Dw+1] != INF:
        ans = cost[Dh+1][Dw+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())

M = ['##' + input() + '##' for _ in range(h)]
for i in range(2):
    M.insert(0,'#'*(w+4))
    M.append('#'*(w+4))

INF = float('inf')
cost = [[INF for _ in range(w+4)] for _ in range(h+4)]
cost0 = deque()
ans = -1

cost0.append((ch+1, cw+1, 0))
cost[ch+1][cw+1] = 0

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

cost1 = deque()

while cost0:
    h, w, c = cost0.popleft()
    cost1.append((h, w, c))
    
    for i,j in move:
        dh = h + i
        dw = w + j
        if M[dh][dw] == '.' and c < cost[dh][dw]: #コストが高いところから低いところに戻らないようにするため
            cost[dh][dw] = c
            cost0.appendleft((dh, dw, cost[dh][dw]))
    
    if len(cost0) == 0:
        while cost1:
            h, w, c = cost1.popleft()
            for i,j in warp:
                dh = h + i
                dw = w + j
                if M[dh][dw] == '.' and c+1 < cost[dh][dw]:  #無駄なワープをなくすため
                    cost[dh][dw] = c+1
                    cost0.append((dh, dw, cost[dh][dw]))
    if cost[Dh+1][Dw+1] != INF:
        ans = cost[Dh+1][Dw+1]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(lambda x : int(x) - 1, input().split())
Dh, Dw = map(lambda x : int(x) - 1, input().split())
maze = [input() for _ in range(H)]

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

#walk:移動A、warp:移動B
walk = [(0, 1), (0, -1), (-1, 0), (1,0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0,0)] + walk]

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def solve():
  h,w=map(int,input().split())
  cy,cx=map(int,input().split())
  dy,dx=map(int,input().split())

  M=["##"+input()+"##" for x in range(h)]
  for i in range(2):
    M.insert(0,"#"*(w+4))
    M.append("#"*(w+4))

  INF=10**6
  C=[[INF for _ in range(w+4)] for _ in range(h+4)]
  C[-~cy][-~cx]=0
  QA,QB=deque(),deque()
  QA.append((-~cy,-~cx,0))
  W=[[i,j] for i in range(-2,3) for j in range(-2,3) if abs(i)+abs(j)>1]

  while QA:
    h,w,c=QA.popleft()
    QB.append((h,w,c))

    for i,j in [[1,0],[0,1],[-1,0],[0,-1]]:
      dh,dw=h+i,w+j
      if M[dh][dw]=="." and c<C[dh][dw]:
        C[dh][dw]=c
        QA.appendleft((dh,dw,c))

    if QA:
      continue

    while QB:
      h,w,c=QB.popleft()
      for i,j in W:
        dh,dw=h+i,w+j
        if M[dh][dw]=="." and -~c<C[dh][dw]:
          C[dh][dw]=-~c
          QA.append((dh,dw,-~c))

  print(C[-~dy][-~dx] if C[-~dy][-~dx]!=INF else -1)

if __name__ == "__main__":
  solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def solve():
  h,w=map(int,input().split())
  cy,cx=map(int,input().split())
  dy,dx=map(int,input().split())

  M=[]
  for i in range(2):
    M.append("#"*(w+4))
  for i in range(h):
    M.append("##"+input()+"##")
  for i in range(2):
    M.append("#"*(w+4))

  INF=10**6
  C=[[INF for _ in range(w+4)] for _ in range(h+4)]
  C[-~cy][-~cx]=0
  QA,QB=deque(),deque()
  QA.append((-~cy,-~cx,0))
  W=[[i,j] for i in range(-2,3) for j in range(-2,3) if abs(i)+abs(j)>1]

  while QA:
    h,w,c=QA.popleft()
    for i,j in [[1,0],[0,1],[-1,0],[0,-1]]:
      if M[h+i][w+j]=='#':
        QB.append((h,w,c))
        break

    for i,j in [[1,0],[0,1],[-1,0],[0,-1]]:
      dh,dw=h+i,w+j
      if M[dh][dw]=="." and c<C[dh][dw]:
        C[dh][dw]=c
        QA.appendleft((dh,dw,c))

    if QA:
      continue

    while QB:
      h,w,c=QB.popleft()
      for i,j in W:
        dh,dw=h+i,w+j
        if M[dh][dw]=="." and -~c<C[dh][dw]:
          C[dh][dw]=-~c
          QA.append((dh,dw,-~c))

  print(C[-~dy][-~dx] if C[-~dy][-~dx]!=INF else -1)

if __name__ == "__main__":
  solve()

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 = [[False]*W for _ in range(H)]
for h in range(H):
    s = input()
    for w in range(W):
        if s[w] == ".":
            S[h][w] = True
d = [[10**9]*W for _ in range(H)]
d[Ch-1][Cw-1] = 0

D = deque([(Ch-1, Cw-1, 0)])
while D:
    h, w, c = deque.popleft(D)
    if c > d[h][w]:
        continue
    # 歩いて移動
    # 上
    if h > 0:
        if S[h-1][w] and c < d[h-1][w]:
            d[h-1][w] = c
            deque.append(D, (h-1, w, c))
    # 下
    if h < H-1:
        if S[h+1][w] and c < d[h+1][w]:
            d[h+1][w] = c
            deque.append(D, (h+1, w, c))
    # 左
    if w > 0:
        if S[h][w-1] and c < d[h][w-1]:
            d[h][w-1] = c
            deque.append(D, (h, w-1, c))
    # 右
    if w < W-1:
        if S[h][w+1] and c < d[h][w+1]:
            d[h][w+1] = c
            deque.append(D, (h, w+1, c))
    # ワープで移動
    for hh in range(max(0, h-2), min(H-1, h+2)+1):
        for ww in range(max(0, w-2), min(W-1, w+2)+1):
            if S[hh][ww] and d[hh][ww] > c+1:
                d[hh][ww] = c+1
                deque.append(D, (hh, ww, c+1))
if d[Dh-1][Dw-1] == 10**9:
    print(-1)
else:
    print(d[Dh-1][Dw-1])