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:
def main():
    import sys
    from collections import deque
    input = sys.stdin.readline
    H, W = [int(x) for x in input().strip().split()]
    Ch, Cw = [int(x)-1 for x in input().strip().split()]
    Dh, Dw = [int(x)-1 for x in input().strip().split()]
    M = [W for _ in range(H)]
    for h in range(H):
        M[h] = list(input().strip())
        # print(M[h])
    ans = 0
    q = deque([(Dh, Dw)])
    while True:
        h, w = q.pop()
        # print('({}, {}) = {}'.format(h, w, ans))
        M[h][w] = ans
        if h == Ch and w == Cw:
            print(ans)
            return True
        for dh, dw in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            if 0 <= h+dh < H and 0 <= w+dw < W and M[h+dh][w+dw] == '.':
                q.append((h+dh, w+dw))
        if len(q) == 0:
            # for h in range(H):
            #     print(M[h])
            f = False
            for h in range(H):
                for w in range(W):
                    if M[h][w] != '.':
                        continue
                    for i, j in [(-2, 2), (-1, 2), (0, 2), (1, 2), (2, 2), (-2, 1), (-1, 1), (1, 1), (2, 1), (-2, 0), (2, 0), (-2, -1), (-1, -1), (1, -1), (2, -1), (-2, -2), (-1, -2), (0, -2), (1, -2), (2, -2)]:
                        if 0 <= h+i < H and 0 <= w+j < W and M[h+i][w+j] == ans:
                            f = True
                            # print('warp to ({}, {})'.format(h, w))
                            q.append((h, w))
            if f:
                ans += 1
            else:
                print(-1)
                return True

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict,deque,Counter
from fractions import Fraction
import bisect
import itertools
from itertools import accumulate
from copy import deepcopy
from queue import PriorityQueue
import heapq
import random
import time
import os
import sys
from functools import lru_cache,reduce
readline=sys.stdin.readline
sys.setrecursionlimit(100000)
alp="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):print("yes" if b else "no")
def Yn(b):print("Yes" if b else "No")
def YN(b):print("YES" if b else "NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(b,t,f):return t if b else f
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def inputintlist(row=1): 
    if row==1:
        ret=list(map(int,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=int(input())
    return ret
def inputfloatlist(row=1): 
    if row==1:
        ret=list(map(float,input().split()))
    else:
        ret=[None]*row
        for a in range(row):
            ret[a]=float(input())
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def zipsort(*args):
    ziplist=sorted(zip(*args))
    for a in range(len(args)):
        for b in range(len(ziplist)):
            args[a][b]=ziplist[b][a]
def zipreverse(*args):
    ziplist=list(zip(*args))
    rev=[]
    for a in range(len(ziplist)-1,-1,-1):
        rev.append(ziplist[a])
    for a in range(len(args)):
        for b in range(len(rev)):
            args[a][b]=rev[b][a]

def to10(A):
    ret=0
    for a in range(len(A)-1,-1,-1):
        ret+=X[a]*2**(N-1-a)
    return ret
######################################################################################################
H,W=inputintlist()
Ch,Cw=inputintlist()
Dh,Dw=inputintlist()
Ch-=1
Cw-=1
Dh-=1
Dw-=1
S=[]
for a in range(H):
    S.append(readline())
edges=[]
for x in range(W):
    for y in range(H):
        dx=[-1,0,1,0]
        dy=[0,1,0,-1]
        for a in range(4):
            tox=x+dx[a]
            toy=y+dy[a]
            if tox<0 or W<=tox:continue
            if toy<0 or H<=toy:continue
            if S[toy][tox]=="#":continue
            edge=Edge(y*W+x,toy*W+tox,0)
            edges.append(edge)
        for a in range(-2,3):
            for b in range(-2,3):
                tox=x+a
                toy=y+b
                if tox<0 or W<=tox:continue
                if toy<0 or H<=toy:continue
                if a==0 and b==0:continue
                if S[toy][tox]=="#":continue
                edge=Edge(y*W+x,toy*W+tox,1)
                edges.append(edge)

        

mincost=dijkstra(edges,H*W,Ch*W+Cw)[Dh*W+Dw]
if mincost==inf:print(-1)
else:print(mincost)

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
ch,cw = map(int,input().split())
dh,dw = map(int,input().split())
s = [list(input()) for i in range(h)]
candidate_0 = [(1,0),(0,1),(-1,0),(0,-1)]
candidate = []
for i in [-2,-1,0,1,2]:
    for j in [-2,-1,0,1,2]:
        if (i == 0 and j == 0):continue
        candidate.append((i,j))


from collections import deque
import math

maze = s.copy()
maze[ch-1][cw-1] = 0
for y in range(h):
    for x in range(w):
        if maze[y][x] == '.':
            maze[y][x] = math.inf
que = deque([[ch-1,cw-1]])
while que:
    y,x = que.popleft()
  
    for i,j in candidate:
        if (i,j) in candidate_0:
            nexty,nextx=y+i,x+j
            if (nexty < 0) or (nextx < 0) or (nexty >= h) or (nextx >= w):continue
            dist = maze[nexty][nextx]
            if dist != '#':
                if dist>maze[y][x]:
                    maze[nexty][nextx]=maze[y][x]
                    que.append([nexty,nextx])            
            
        else:
            nexty,nextx=y+i,x+j
            if (nexty < 0) or (nextx < 0) or (nexty >= h) or (nextx >= w):continue
            dist = maze[nexty][nextx]
            if dist != '#':
                if dist>maze[y][x]+1:
                    maze[nexty][nextx]=maze[y][x]+1
                    que.append([nexty,nextx])
            
if maze[dh-1][dw-1] == math.inf:
    print(-1)
else:
    print(maze[dh-1][dw-1])

Submission status: Time Limit Exceeded

Solution code:
def main():
    from sys import stdin
    from collections import deque
    import sys
    H, W = map(int, stdin.readline().split())
    ch, cw = map(int, stdin.readline().split())
    dh, dw = map(int, stdin.readline().split())
    ch, cw, dh, dw = ch-1, cw-1, dh-1, dw-1
    S = [input() for _ in range(H)]
    d = [[0]*W for _ in range(H)]

    que = deque([[cw, ch]])
    count = 0
    while que:
        while que:
            x, y = que.popleft()
            if x == dw and y == dh:
                print(count)
                sys.exit()
                
            d[y][x] = -1
            for i in range(-2, 3):
                for j in range(-2, 3):
                    nnx, nny = x+i, y+j
                    if 0<=nnx<W and 0<=nny<H and d[nny][nnx]==0 and S[nny][nnx]!='#':
                        d[nny][nnx] = 1
        
            for dx, dy in [1, 0], [0, 1], [-1, 0], [0, -1]:
                nx, ny = x+dx, y+dy
                if 0<=nx<W and 0<=ny<H and S[ny][nx]!='#' and d[ny][nx]!=-1:
                    if nx == dw and ny == dh:
                        print(count)
                        sys.exit()
                
                    d[ny][nx] = -1
                    for i in range(-2, 3):
                        for j in range(-2, 3):
                            nnx, nny = nx+i, ny+j
                            if 0<=nnx<W and 0<=nny<H and d[nny][nnx]==0 and S[nny][nnx]!='#':
                                d[nny][nnx] = 1
                    que.append([nx, ny])
                
        for i in range(W):
            for j in range(H):
                if d[j][i] == 1:
                    d[j][i] == -1
                    que.append([i, j])
        count += 1
    print(-1)

main()

Submission status: Time Limit Exceeded

Solution code:
import collections, sys
input = sys.stdin.readline

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(list(input()))
num = [[float("inf") for i in range(w)] for i in range(h)]
flag = [[False for i in range(w)] for i in range(h)]
num[ch - 1][cw - 1] = 0
queue = collections.deque([[ch, cw]])
d1 = [[-1, 0], [1, 0], [0, -1], [0, 1]]
d2 = [[-1, -1], [-1, 1], [1, -1], [1, 1], [-2, 0], [2, 0], [0, -2], [0, 2]]
d3 = [[-2, -1], [-1, -2], [2, -1], [1, -2], [-2, 1], [-1, 2], [2, 1], [1, 2]]
d4 = [[-2, -2], [-2, 2], [2, -2], [2, 2]]
while queue:
    test = queue.popleft()
    x = test[0]
    y = test[1]
    flag[y - 1][x - 1] = True
    temp = num[y - 1][x - 1]
    for i in d1:
        x2 = x + i[0]
        y2 = y + i[1]
        if 1 <= x2 <= w and 1 <= y2 <= h and s[y2 - 1][x2 - 1] == "." and flag[y2 - 1][x2 - 1] == False:
            num[y2 - 1][x2 - 1] = temp
            queue.append([x2, y2])
    for i in d2:
        x2 = x + i[0]
        y2 = y + i[1]
        if 1 <= x2 <= w and 1 <= y2 <= h and s[y2 - 1][x2 - 1] == "." and flag[y2 - 1][x2 - 1] == False:
            num[y2 - 1][x2 - 1] = min(temp + 1, num[y2 - 1][x2 - 1])
            queue.append([x2, y2])
    for i in d3:
        x2 = x + i[0]
        y2 = y + i[1]
        if 1 <= x2 <= w and 1 <= y2 <= h and s[y2 - 1][x2 - 1] == "." and flag[y2 - 1][x2 - 1] == False:
            num[y2 - 1][x2 - 1] = min(temp + 1, num[y2 - 1][x2 - 1])
            queue.append([x2, y2])
    for i in d4:
        x2 = x + i[0]
        y2 = y + i[1]
        if 1 <= x2 <= w and 1 <= y2 <= h and s[y2 - 1][x2 - 1] == "." and flag[y2 - 1][x2 - 1] == False:
            num[y2 - 1][x2 - 1] = min(temp + 1, num[y2 - 1][x2 - 1])
            queue.append([x2, y2])
if num[dh - 1][dw - 1] == float("inf"):
    print(-1)
else:
    print(num[dh - 1][dw - 1])

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(1000000)

def main():
    H, W = map(int, input().split())
    ch, cw = map(int, input().split())
    dh, dw = map(int, input().split())
    S = [0] * H
    for i in range(H):
        S[i] = list(input().split()[0])

    res_map = [[-1] * W for i in range(H)]
    res_map[ch-1][cw-1] = 0

    def dfs(xi, yi):
        current_cost = res_map[xi][yi]
        for dx in range(-2,3):
            for dy in range(-2,3):
                x = xi + dx
                y = yi + dy
                dist = abs(dx) + abs(dy)
                if dist > 1:
                    cost = current_cost + 1
                else:
                    cost = current_cost 
                if 0 <= x and x < H and 0 <= y and y < W:
                    if S[x][y] == "." and (res_map[x][y] > cost or res_map[x][y] == -1):
                        res_map[x][y] = cost
                        dfs(x,y)

    dfs(ch-1, cw-1)
    print(res_map[dh-1][dw-1])

if __name__ == "__main__":
    main()

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())
ch-=1; cw-=1; dh-=1; dw-=1
area = [list(input()) for _ in range(h)]
dist = [[-1]*w for i in range(h)]

dk = [(i, j, 0) for i in range(-2, 3) for j in range(-2, 3)]
d = []
for i, j, c in dk:
    if (i, j) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        c = 0
    else:
        c = 1
    d.append((c, i, j))

def Dijkstra(ch, cw):
    """
    Dijkstra法を用いて単一始点終点の最短コストを算出する
    0オリジンとする。
    es: 辺を表す配列。
        es[start]: [cost, en]
    n: 頂点数
    source: 始点
    return: dist　最短距離距離配列。
    """
    import heapq
    used = [[False] * w for i in range(h)] # Falseならば計算対象
    edgelist = []
    # 始点の辺を追加
    for e in d:
        c, y, x = e
        if 0<=ch+y<h and 0<=cw+x<w:
            if used[ch+y][cw+x]: continue
            if area[ch+y][cw+x]=='#': continue
            heapq.heappush(edgelist, (c, ch+y, cw+x))
    used[ch][cw] = True
    dist[ch][cw] = 0
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        cost, y, x = minedge
        if used[y][x]:
            continue
        dist[y][x] = cost
        used[y][x] = True
        if y==dh and x==dw:
            return dist
        for e in d:
            next_cost, next_y, next_x = e
            if 0<=y+next_y<h and 0<=x+next_x<w:
                if used[y+next_y][x+next_x]: continue
                if area[y+next_y][x+next_x]=='#': continue
                heapq.heappush(edgelist, (dist[y][x]+next_cost, y+next_y, x+next_x))
    return dist

dist = Dijkstra(ch, cw)
print(dist[dh][dw])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w = map(int,input().split())
sh,sw = map(int,input().split())
gh,gw = map(int,input().split())
s = [input() for _ in range(h)]

sh-=1; sw-=1; gh-=1; gw-=1;

dist = [[-1]*w for _ in range(h)]
dist[sh][sw] = 0
q = deque([(0,sh,sw)])
warpq = deque([])

while q or warpq:
    while q:

        d,vsh,vsw = q.popleft()

        flag = 0
        
        for dh,dw in [(-1,0),(1,0),(0,-1),(0,1)]:
            newh = vsh+dh
            neww = vsw+dw
            if newh<0 or h<=newh or neww<0 or w<=neww: continue
            if s[newh][neww] == "#":
                if flag ==0:
                    warpq.append((d,vsh,vsw))
                    flag = 1
                continue

            if dist[newh][neww] == -1:
                dist[newh][neww] = d
                q.append((d,newh,neww))

    while warpq:

        d,vsh,vsw = warpq.popleft()
        for dh in range(-2,3):
            for dw in range(-2,3):
                newh = vsh+dh
                neww = vsw+dw
                if newh<0 or h<=newh or neww<0 or w<=neww: continue
                if abs(dh)+abs(dw)<=0: continue
                if s[newh][neww] == "#": continue

                if dist[newh][neww] == -1:
                    dist[newh][neww] = d+1
                    q.append((d+1,newh,neww))
            
print(dist[gh][gw])

Submission status: Time Limit Exceeded

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce, lru_cache
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

H, W = MAP()
Ch, Cw = MAP()
Dh, Dw = MAP()
S = [input() for _ in range(H)]

cnt = [[INF]*W for _ in range(H)]
cnt[Ch-1][Cw-1] = 0

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

def wizard_cnt(start_y, start_x):
	q = deque([(start_y, start_x)])
	while q:
		y, x = q.pop()
		flg = True
		for i in range(24):
			if i == 4 and flg:
				break
			ny = y + dy[i]
			nx = x + dx[i]
			if ny < 0 or nx < 0 or H <= ny or W <= nx:
				continue
			elif i < 4:
				if S[ny][nx] == "." and cnt[y][x] < cnt[ny][nx]:
					cnt[ny][nx] = cnt[y][x]
					q.append((ny, nx))
				elif S[ny][nx] == "#":
					flg = False
			elif 4 <= i and S[ny][nx] == "." and cnt[y][x]+1 < cnt[ny][nx]:
				cnt[ny][nx] = cnt[y][x]+1
				q.append((ny, nx))

wizard_cnt(Ch-1, Cw-1)

if cnt[Dh-1][Dw-1] == INF:
	print(-1)
else:
	print(cnt[Dh-1][Dw-1])

Submission status: Time Limit Exceeded

Solution code:
xy=[(1,0),(-1,0),(0,1),(0,-1)]
wp=[(-1,-1),(-1,1),(1,1),(1,-1),(2,0),(-2,0),(0,2),(0,-2),(-2,-1),(-2,1),(2,1),(2,-1),(-1,-2),(-1,2),(1,2),(1,-2),(-2,-2),(-2,2),(2,2),(2,-2)]
#t=[[0]*5 for i in range(5)]
#x=y=2
#for i,j in wp:
#    i+=x
#    j+=x
#    t[i][j]=7
#for i in t:
#    print(i)
#exit()

h,w=map(int,input().split())
c1,c2=map(int,input().split())
d1,d2=map(int,input().split())
d=[list(input()) for i in range(h)]
d[c1-1][c2-1]=0
p=set([(c1-1,c2-1)])
while len(p):
    a,b=p.pop()
    for x,y in xy:
        x+=a
        y+=b
        if 0<=x<h and 0<=y<w and d[x][y]!="#":
            if d[x][y]=="." or d[x][y]>d[a][b]:
                d[x][y]=d[a][b]
                p.add((x,y))
    for x,y in wp:
        x+=a
        y+=b
        if 0<=x<h and 0<=y<w and d[x][y]!="#":
            if d[x][y]=="." or d[x][y]>d[a][b]+1:
                d[x][y]=d[a][b]+1
                p.add((x,y))

print(-1 if (d[d1-1][d2-1]=="#" or d[d1-1][d2-1]==".") else d[d1-1][d2-1])

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, setrecursionlimit
from collections import Counter, deque, defaultdict
from heapq import heapify, heappush, heappop
from math import floor, ceil
from bisect import bisect_left
from itertools import combinations
setrecursionlimit(100000)

INF = int(1e10)
MOD = int(1e9 + 7)

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

def main():
    from builtins import int, map
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    Ch, Cw = Ch - 1, Cw - 1
    Dh, Dw = Dh - 1, Dw - 1
    S = [list(input()) for _ in range(H)]
    counter = 0
    for h in range(H):
        for w in range(W):
            if S[h][w] == '.':
                counter += 1
    # for row in S: print(*row)

    # 連結成分を調べる
    num_con = {}
    for h in range(H):
        for w in range(W):
            if S[h][w] == '.':
                num_con[h, w] = None

    ncon_num = 0
    for h in range(H):
        for w in range(W):
            # 既に決まっていたらいらない
            if S[h][w] != '.' or num_con[h, w] != None:
                continue
            num_con[h, w] = ncon_num
            dist = defaultdict(lambda: float("inf"))
            dist[h, w] = 0
            queue = []
            heappush(queue, (0, (h, w)))
            visited = set({})

            while queue:
                d, (nh, nw) = heappop(queue)
                dist[nh, nw] = d
                num_con[nh, nw] = ncon_num
                visited.add((nh, nw))

                if dist[nh, nw] < d:
                    continue

                for i in range(4):
                    dhi, dwi = dh[i], dw[i]
                    nnh, nnw = nh + dhi, nw + dwi
                    if 0 <= nnh < H and 0 <= nnw < W and S[nnh][nnw] != '#':
                        if num_con[nnh, nnw] is None:
                            # if (nnh, nnw) not in visited:
                            heappush(queue, (d, (nnh, nnw)))

            # 次
            ncon_num += 1

    if ncon_num == 1:
        print(0)
        exit()
            
    con_nodes = defaultdict(set)
    start_con = None
    goal_con = None
    for h in range(H):
        for w in range(W):
            if S[h][w] == '.':
                con_nodes[num_con[h, w]].add((h, w))
                if (h, w) == (Ch, Cw):
                    start_con = num_con[h, w]
                if (h, w) == (Dh, Dw):
                    goal_con = num_con[h, w]
    ncon = len(con_nodes)

    # pair-wiseに調べる
    # print(ncon, start_con, goal_con)
    dist_mat = [[float("inf")] * ncon for _ in range(ncon)]
    for g1 in range(ncon):
        for g2 in range(ncon):
            if g1 == g2:
                dist_mat[g1][g2] = dist_mat[g2][g1] = 0
            else:
                flag = False
                for (h1, w1) in con_nodes[g1]:
                    for (h2, w2) in con_nodes[g2]:
                        ddh = abs(h1 - h2)
                        ddw = abs(w1 - w2)
                        if ddh <= 2 and ddw <= 2:
                            flag = True
                            break
                    if flag:
                        break
                if flag:
                    dist_mat[g1][g2] = dist_mat[g2][g1] = 1

    # for dd in dist_mat: print(*dd)

    # 作成したグラフでDijkstra
    dist = [float("inf")] * ncon
    dist[start_con] = 0
    queue = [(0, start_con)]
    while queue:
        dc, c = heappop(queue)
        if dist[c] < dc:
            continue

        for cc in range(ncon):
            cost = dist_mat[c][cc]
            if dist != float("inf") and dist[cc] > dist[c] + cost:
                dist[cc] = dist[c] + cost
                heappush(queue, (dist[cc], cc))

    if dist[goal_con] == float("inf"):
        print(-1)
    else:
        print(dist[goal_con])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())

S = [0 for i in range(H+4)]
S[0] = "#"*(W+4)
S[1] = "#"*(W+4)
S[H+2] = "#"*(W+4)
S[H+3] = "#"*(W+4)
for i in range(2, H+2):
  S[i] = "##" + input() + "##"
  
B = [ [-1 for i in range(W+4)] for i in range(H+4)]

def search(i,j,c):
  global B
  B[i][j] = c
  L = [(-1,0), (1, 0), (0, -1), (0, 1)]
  for X in L:
    if S[i+X[0]][j+X[1]] == '.' and B[i+X[0]][j+X[1]] < 0:
        search(i+X[0],j+X[1],c)
        
#<01>[2--H+1]<H+2,3>#
c = 0
for i in range(2,H+2):
  for j in range(2,W+2):
    if S[i][j] == '.' and B[i][j] < 0:
      search(i, j, c)
      c += 1

Cc = B[Ch+1][Cw+1]
Dc = B[Dh+1][Dw+1]
dic = {i:set() for i in range(c)}

for i in range(2, H+2):
  for j in range(2, W+2):
    if B[i][j] >= 0:
      for x in range(-2, 3):
        for y in range(-2, 3):
          if S[i+x][j+y] == '.' and B[i][j] != B[i+x][j+y]:
            dic[B[i][j]].add(B[i+x][j+y])

ans = [-1 for i in range(c)]
ans[Cc] = 0
not_check = [1 for i in range(c)]
not_check[Cc] = 0
next_check = {Cc}
#
t = 0
while len( next_check ):
  t += 1
  tmp = set()
  for i in next_check:
    for j in dic[i]:
      if not_check[j]:
        not_check[j] = 0
        ans[j] = t
        tmp.add( j )
  next_check = {i for i in tmp}
#
print(ans[Dc])