Problem:


Score : 400 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

1

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

Note that he cannot walk diagonally.

Sample Input 2

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

Sample Output 2

-1

He cannot move from there.

Sample Input 3

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

Sample Output 3

0

No use of magic is needed.

Sample Input 4

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

Sample Output 4

2



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


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
from heapq import heapify, heappop, heappush
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
input = sys.stdin.readline

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
S = [input().rstrip() for _ in [0]*H]

INF = 10**10
D = [[INF]*W for _ in [0]*H]
used = set()

q = []
heappush(q, (0, Ch, Cw))

dirs = [(-1, 0), (1, 0), (0, 1), (0, -1)]
wps = [
    [(-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2), (-1, -1), (-1, 1)],
    [(2, 2), (2, -1), (2, 0), (2, 1), (2, 2), (1, -1), (1, 1)],
    [(-2, 2), (-1, 2), (0, 2), (1, 2), (2, 2), (-1, 1), (1, 1)],
    [(-2, -2), (-1, -2), (0, -2), (1, -2), (2, -2), (-1, -1), (1, -1)]
]

while q:
    d, i, j = heappop(q)
    used.add((i, j))
    if D[i][j] > d:
        D[i][j] = d
    else:
        continue
    if i == Dh and j == Dw:
        break

    for k, (di, dj) in enumerate(dirs):
        _i = i + di
        _j = j + dj
        if 0 <= _i < H and 0 <= _j < W:
            if (_i, _j) in used:
                continue
            if S[_i][_j] == '.':
                used.add((_i, _j))
                heappush(q, (d, _i, _j))
            else:
                for di, dj in wps[k]:
                    _i = i + di
                    _j = j + dj
                    if 0 <= _i < H and 0 <= _j < W and (_i, _j) not in used and S[_i][_j] == '.':
                        heappush(q, (d+1, _i, _j))

ans = D[Dh][Dw]
print(ans if ans < INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w=map(int,input().split())

def main():
    start = tuple(x-1 for x in map(int,input().split()))
    goal = tuple(x-1 for x in map(int,input().split()))
    s = [input() for _ in range(h)]
    
    sumi = set()
    cur = 0
    ans = [[-1]*w for _ in range(h)]
    srch = deque([start])
    warp_can = set()
    while len(srch) > 0:
        while len(srch) > 0:
            c=srch.popleft()
            ans[c[0]][c[1]] = cur
            if c in sumi:
                continue
            sumi.add(c)
            warp_can |= set(getwarp(c,s,sumi))
            for x,y in getnext(c):
                #print(c,x,y,h,w)
                if s[x][y] == "#" or (x,y) in sumi:
                    continue
                srch.append((x,y))
        srch += list(warp_can - sumi)
        cur += 1
        #if input() =="break":
        #    break
    #for i in ans:
    #        print(i)
    print(ans[goal[0]][goal[1]])

def getnext(c):
    if 0 < c[0]:
        yield (c[0]-1, c[1])
    if c[0]+1 < h:
        yield (c[0]+1, c[1])
    if 0 < c[1]:
        yield (c[0], c[1]-1)
    if c[1]+1 < w:
        yield (c[0], c[1]+1)

def getwarp(c,s,sumi):
    for x in range(-2,3):
        for y in range(-2,3):
            cx,cy=c[0]+x,c[1]+y
            if 0 <= cx < h and 0 <= cy < w:
                if s[cx][cy] == "#" or (cx,cy) in sumi:
                    continue
                yield (cx,cy)

if __name__ == '__main__':
    main()

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()))

import heapq
seen = set()
queue = [(0, CH-1, CW-1)]

while queue:
    move, row, col = heapq.heappop(queue)

    # print(row, col, S[row][col], move, queue)
    if row == DH-1 and col == DW-1:
        print(move)
        sys.exit(0)

    if (row, col) in seen:
        continue

    seen.add((row, col))

    for r_offset, c_offset in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        new_row = row + r_offset
        new_col = col + c_offset
        # print(new_row, new_col)
        if 0 <= new_row < H and 0 <= new_col < W and S[new_row][new_col] == '.':
            heapq.heappush(queue, (move, new_row, new_col))


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

            if 0 <= new_row < H and 0 <= new_col < W and S[new_row][new_col] == '.':
                heapq.heappush(queue, (move+1, new_row, new_col))

print(-1)

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 -1<=a and a<=1 and b==0:continue
                if -1<=b and b<=1 and a==0:continue
                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,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 = list(map(int, input().split()))
ch, cw = list(map(int, input().split()))
dh, dw = list(map(int, input().split()))
ch -= 1
cw -= 1
dh -= 1
dw -= 1
s = []
for i in range(h):
  s.append(input().strip())


o = set()
e = {(ch, cw)}

def walk(e):
  ne = set(e)
  def sub(xe):
    xxe = set()
    for nh, nw in xe:
      for mh, mw in [(nh+1, nw), (nh-1, nw), (nh, nw+1), (nh, nw-1)]:
        if (mh, mw) in ne or (mh, mw) in o:
          continue
        if mh < 0 or h <= mh or mw < 0 or w <= mw:
          continue
        if s[mh][mw] == '.':
          ne.add((mh, mw))
          xxe.add((mh, mw))
    return xxe 
  while(e):
    e = sub(e)
  return ne

def warp(e):
  ne = set()
  for nh, nw in e:
    for mh in range(max(0, nh-2), min(nh+3, h)):
      for mw in range(max(0, nw-2), min(nw+3, w)):
        if nh == mh and nw == mw or (mh, mw) in o:
          continue
        if s[mh][mw] == '.':
          ne.add((mh, mw))
  return ne

import sys

ww = 0

while(len(e) > 0):
  if (dh, dw) in e:
    print(ww)
    sys.exit()
  ne = walk(e)
  if (dh, dw) in ne:
    print(ww)
    sys.exit()
  o.update(e)
  e = ne
  ne = warp(e)
  ww += 1
  if (dh, dw) in ne:
    print(ww)
    sys.exit()
  o.update(e)
  e = ne
print('-1')

Submission status: Time Limit Exceeded

Solution code:
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    H, W = [int(x) for x in input().split()]
    CH, CW = [int(x) - 1 for x in input().split()]
    DH, DW = [int(x) - 1 for x in input().split()]
    S = [input().strip() for _ in range(H)]

    warp = ((-2, -2), (-2, -2), (-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))

    visited = [[10 ** 6] * W for _ in range(H)]

    q = collections.deque()
    visited[CH][CW] = 0
    q.append((CH, CW))
    while q:
        cx, cy = q.popleft()
        cc = visited[cx][cy]

        # 隣接
        kabe_cnt = 0
        for nx, ny in ([0, 1], [0, -1], [1, 0], [-1, 0]):
            nnx = cx + nx
            nny = cy + ny
            if 0 <= nnx <= H - 1 and 0 <= nny <= W - 1:
                if S[nnx][nny] == ".":
                    if visited[nnx][nny] > cc:
                        q.append((nnx, nny))
                        visited[nnx][nny] = cc
                else:
                    kabe_cnt += 1

        # ワープ
        if kabe_cnt > 0:
            for nx, ny in warp:
                nnx = cx + nx
                nny = cy + ny
                if 0 <= nnx <= H - 1 and 0 <= nny <= W - 1:
                    if S[nnx][nny] == "." and visited[nnx][nny] > cc:
                        q.append((nnx, nny))
                        visited[nnx][nny] = cc + 1

    if visited[DH][DW] == 10 ** 6:
        print(-1)
    else:
        print(visited[DH][DW])


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

# S = [["." if j % 2 == 0 else "#" for j in range(W)] for i in range(H)]
# S[0][0] = "."
# S[DH-1][DW-1] = "."

# for i in range(H):
#     print(S[i])

from collections import deque

q = deque([(CH-1, CW-1)])

directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
warp = [(-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2),
        (-1, -2), (-1, -1), (-1, 0), (-1, 1), (-1, 2),
        (0, -2), (0, -1), (0, 1), (0, 2),
        (1, -2), (1, -1), (1, 0), (1, 1), (1, 2),
        (2, -2), (2, -1), (2, 0), (2, 1), (2, 2)]
# 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)]

M = []
for i in range(H):
    M.append([10**9] * W)
M[CH-1][CW-1] = 0

# for i in range(H):
#     visited.append([False] * W)
# visited[CH-1][CW-1] = True

visited = deque([(CH-1, CW-1)])
while True:
    while q:
        h, w = q.popleft()
        for dh, dw in directions:
            if 0 <= h+dh < H and 0 <= w+dw < W and S[h+dh][w+dw] == ".":
                if M[h+dh][w+dw] > M[h][w]:
                    M[h+dh][w+dw] = M[h][w]
                    q.append((h+dh, w+dw))
                    visited.append((h+dh, w+dw))
                    # print(visited)

    while visited:
        vh, vw = visited.popleft()
        for wh, ww in warp:
            if 0 <= vh+wh < H and 0 <= vw+ww < W and S[vh+wh][vw+ww] == ".":
                if M[vh+wh][vw+ww] > M[vh][vw] + 1:
                    M[vh+wh][vw+ww] = M[vh][vw] + 1
                    q.append((vh+wh, vw+ww))
                    visited.append((vh+wh, vw+ww))
                    # print(visited)
    
    if len(q) == 0:
        break

# for i in range(H):
#     print(M[i])

if M[DH-1][DW-1] == 10**9:
    print(-1)
else:
    print(M[DH-1][DW-1])

Submission status: Time Limit Exceeded

Solution code:
#ダイクストラ法
import heapq
def dijkstra_heap(s):
    #始点sから各頂点への最短距離
    d = [10**18] * h*w
    used = [True] * h*w #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge[1]]:
            continue
        v = minedge[1]
        d[v] = minedge[0]
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,[e[0]+d[v],e[1]])
    return d


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
s=[input() for _ in range(h)]
edge=[[] for _ in range(h*w)]
for i in range(h):
    for j in range(w):
        if s[i][j]=="#":
            continue
        idx=i*w+j
        for dx in range(-2,3):
            for dy in range(-2,3):
                nx=i+dx
                ny=j+dy
                if 0<=nx<h and 0<=ny<w:
                    idx1=nx*w+ny
                    if dx==0 and dy==0:
                        continue
                    if (dx,dy) in [(-1,0),(0,-1),(1,0),(0,1)]:
                        edge[idx].append([0,idx1])
                    else:
                        edge[idx].append([1,idx1])
s=ch*w+cw
g=dh*w+dw
d=dijkstra_heap(s)
ans=d[g]
if ans==10**18:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
C0, C1 = map(int, input().split())
D0, D1 = map(int, input().split())

ARR = []

for i in range(H):
    ARR.append(input())


def calculate(h, w, c0, c1, d0, d1, arr):
    c0 = c0 - 1
    c1 = c1 - 1
    d0 = d0 - 1
    d1 = d1 - 1

    status = []
    for i in range(H):
        tmp = []
        for j in range(W):
            tmp.append(-1)
        status.append(tmp)

    q = deque()

    q.append((c0, c1, 0))

    while len(q) > 0:
        hIndex, wIndex, index = q.popleft()


        if status[hIndex][wIndex] == -1:
            status[hIndex][wIndex] = index
        else:
            if status[hIndex][wIndex] > index:
                status[hIndex][wIndex] = index
            else:
                continue

        for _hIndex in range(hIndex - 2, hIndex + 3):
            for _wIndex in range(wIndex - 2, wIndex + 3):
                if (_hIndex == hIndex) and (_wIndex == wIndex):
                    continue
                if (_hIndex >= 0 and _hIndex < h) and (_wIndex >= 0 and _wIndex < w):
                    if arr[_hIndex][_wIndex] == '.':
                        if (_hIndex == hIndex) and (_wIndex == (wIndex - 1)):
                            tmpIndex = index
                        elif (_hIndex == hIndex) and (_wIndex == (wIndex + 1)):
                            tmpIndex = index
                        elif (_wIndex == wIndex) and (_hIndex == (hIndex - 1)):
                            tmpIndex = index
                        elif (_wIndex == wIndex) and (_hIndex == (hIndex + 1)):
                            tmpIndex = index
                        else:
                            tmpIndex = index + 1

                        if status[_hIndex][_wIndex] == -1:
                            q.append((_hIndex, _wIndex, tmpIndex))
                        elif status[_hIndex][_wIndex] > tmpIndex:
                            q.append((_hIndex, _wIndex, tmpIndex))

    if status[d0][d1] >= 0:
        print(status[d0][d1])
    else:
        print(-1)



calculate(H, W, C0, C1, D0, D1, ARR)

Submission status: Time Limit Exceeded

Solution code:
h, w = map( int, input().split() )
c_h, c_w = map( int, input().split() )
c = ( c_h - 1 ) * w + ( c_w - 1 )
d_h, d_w = map( int, input().split() )
d = ( d_h - 1 ) * w + ( d_w - 1 )
s = []
for _ in range( h ):
    s_h = str( input() )
    # s.append( s_h )
    for s_h_w in s_h:
        s.append( s_h_w )

move_a = []
for i in range( h * w ):
    move_a_i = []
    if i % w > 0:
        if s[ i - 1 ] != "#":
            move_a_i.append( i - 1 )
    if i // w > 0:
        if s[ i - w ] != "#":
            move_a_i.append( i - w )
    if i % w < w - 1:
        if s[ i + 1 ] != "#":
            move_a_i.append( i + 1 )
    if i // w < h - 1:
        if s[ i + w ] != "#":
            move_a_i.append( i + w )
    move_a.append( move_a_i )

move_b = []
for i in range( h * w ):
    move_b_i = []
    if i % w > 1:
        if s[ i - 2 ] != "#":
            move_b_i.append( i - 2 )
    if i % w > 0 and i // w > 0:
        if s[ i - 1 - w ] != "#":
            move_b_i.append( i - 1 - w )
    if i % w > 1 and i // w > 1:
        if s[ i - 2 - 2 * w ] != "#":
            move_b_i.append( i - 2 - 2 * w )
    if i // w > 1:
        if s[ i - 2 * w ] != "#":
            move_b_i.append( i - 2 * w )
    if i // w > 0 and i % w < w - 1:
        if s[ i - w + 1 ] != "#":
            move_b_i.append( i - w + 1 )
    if i // w > 1 and i % w < w - 2:
        if s[ i - 2 * w + 2 ] != "#":
            move_b_i.append( i - 2 * w + 2 )
    if i % w < w - 2:
        if s[ i + 2  ] != "#":
            move_b_i.append( i + 2 )
    if i % w < w - 1 and i // w < h - 1:
        if s[ i + 1 + w ] != "#":
            move_b_i.append( i + 1 + w )
    if i % w < w - 2 and i // w < h - 2:
        if s[ i + 2 + 2 * w  ] != "#":
            move_b_i.append( i + 2 + 2 * w )
    if i // w < h - 2:
        if s[ i + 2 * w  ] != "#":
            move_b_i.append( i + 2 * w )
    if i % w > 0 and i // w < h - 1:
        if s[ i + w - 1 ] != "#":
            move_b_i.append( i + w - 1 )
    if i % w > 1 and i // w < h - 2:
        if s[ i + 2 * w - 2  ] != "#":
            move_b_i.append( i + 2 * w - 2 )

    if i % w > 2 and i // w > 0:
        if s[ i - w - 2  ] != "#":
            move_b_i.append( i - w - 2 )
    if i % w > 1 and i // w > 1:
        if s[ i - 2 * w - 1  ] != "#":
            move_b_i.append( i - 2 * w - 1 )
    if i % w < w - 1 and i // w > 2:
        if s[ i - 2 * w + 1  ] != "#":
            move_b_i.append( i - 2 * w + 1 )
    if i % w < w - 2 and i // w > 1:
        if s[ i - w + 2 ] != "#":
            move_b_i.append( i - w + 2 )
    if i % w < w - 2 and i // w < h - 1:
        if s[ i + w + 2 ] != "#":
            move_b_i.append( i + w + 2 )
    if i % w < w - 1 and i // w < h - 2:
        if s[ i + 2 * w + 1 ] != "#":
            move_b_i.append( i + 2 * w + 1 )
    if i % w > 0 and i // w < h - 2:
        if s[ i + 2 * w - 1 ] != "#":
            move_b_i.append( i + 2 * w - 1 )
    if i % w > 1 and i // w < h - 1:
        if s[ i + w - 2 ] != "#":
            move_b_i.append( i + w - 2 )
    move_b.append( move_b_i )

from heapq import heappush, heappop
INF = 10 ** 10
VISITED = 1
NOT_VISITED = 0
      
cost = [ INF ] * ( h * w )
cost[ c ] = 0
visit = [ NOT_VISITED ] * ( h * w )
visit[ c ] = VISITED
queue = [ ( cost[ c ], c ) ]
while len( queue ) > 0:
    c, v = heappop( queue )
    visit[ v ] = VISITED
    for u in move_a[ v ]:
        if visit[ u ] == VISITED:
            continue
        if cost[ u ] > cost[ v ]:
            cost[ u ] = cost[ v ]
            heappush( queue, ( cost[ u ], u ) )
    if len( move_a[ v ] ) == 4:
        continue
    for t in move_b[ v ]:
        if visit[ t ] == VISITED:
            continue
        if cost[ t ] > cost[ v ] + 1:
            cost[ t ] = cost[ v ] + 1
            heappush( queue, ( cost[ t ], t ) )

if cost[ d ] == INF:
    print( -1 )
else:
    print( cost[ d ] )

Submission status: Time Limit Exceeded

Solution code:
from heapq import heapify, heappop, heappush
import sys
read = sys.stdin.read
readlines = sys.stdin.readlines
input = sys.stdin.readline

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
S = [input().rstrip() for _ in [0]*H]

INF = 10**10
D = [[INF]*W for _ in [0]*H]
used = set()

q = []
heappush(q, (0, Ch, Cw))

dirs = [(-1, 0), (1, 0), (0, 1), (0, -1)]
wps = [
    [(-2, -2), (-2, -1), (-2, 0), (-2, 1), (-2, 2), (-1, -1), (-1, 1)],
    [(2, 2), (2, -1), (2, 0), (2, 1), (2, 2), (1, -1), (1, 1)],
    [(-2, 2), (-1, 2), (0, 2), (1, 2), (2, 2), (-1, 1), (1, 1)],
    [(-2, -2), (-1, -2), (0, -2), (1, -2), (2, -2), (-1, -1), (1, -1)]
]

while q:
    d, i, j = heappop(q)
    used.add((i, j))
    D[i][j] = d
    if i == Dh and j == Dw:
        break

    for k, (di, dj) in enumerate(dirs):
        _i = i + di
        _j = j + dj
        if 0 <= _i < H and 0 <= _j < W:
            if (_i, _j) in used:
                continue
            if S[_i][_j] == '.':
                used.add((_i, _j))
                heappush(q, (d, _i, _j))
            else:
                for di, dj in wps[k]:
                    _i = i + di
                    _j = j + dj
                    if 0 <= _i < H and 0 <= _j < W and (_i, _j) not in used and S[_i][_j] == '.':
                        heappush(q, (d+1, _i, _j))

ans = D[Dh][Dw]
print(ans if ans < INF else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
H,W = map(int,input().split())
CH,CW = map(int,input().split())
DH,DW = map(int,input().split())
S = 2*[(W+4)*["#"]]+[2*["#"]+list(input())+2*["#"] for h in range(H)]+2*[(W+4)*["#"]]
S[CH+1][CW+1] = 0
P = [[CH+1,CW+1]]
Q = deque([[CH+1,CW+1]])
ans = 0

while P:
  P = []
  while Q:
    y,x = Q.popleft()
    P+=[[y,x]]
    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      if S[y+dy][x+dx]==".":
        S[y+dy][x+dx] = S[y][x]
        Q+=[[y+dy,x+dx]]

  if S[DH+1][DW+1]!=".":
    print(S[DH+1][DW+1])
    exit()
  else:
    ans+=1
    for y,x in P:
      for dy,dx in [[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]]:
        if S[y+dy][x+dx]==".":
          S[y+dy][x+dx] = ans
          Q+=[[y+dy,x+dx]]

if S[DH+1][DW+1]==".":
  print(-1)
else:
  print(S[DH+1][DW+1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

grid = []
for i in range(H):
    grid.append(input().rstrip())

d = deque()
d.append((Ch-1, Cw-1, 0))

memo = [[[False] * W for _ in range(H)] for _ in range(1000)]
memo[0][Ch-1][Cw-1] = True

searched = [[False] * W for _ in range(H)]

ans = -1

while d:
    h, w, c = d.popleft()

    if searched[h][w]:
        continue

    searched[h][w] = True

    if h == Dh-1 and w == Dw-1:
        ans = c
        break

    for i, j in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        if 0 <= h+i < H and 0 <= w+j < W:
            if grid[h+i][w+j] == '.':
                if not memo[c][h+i][w+j]:
                    memo[c][h+i][w+j] = True
                    d.appendleft((h+i, w+j, c))

    for i in range(-2, 3):
        for j in range(-2, 3):
            if 0 <= h+i < H and 0 <= w+j < W:
                if grid[h+i][w+j] == '.':
                    if not memo[c][h+i][w+j] and not memo[c+1][h+i][w+j] and not searched[h+i][w+j]:
                        memo[c+1][h+i][w+j] = True
                        d.append((h+i, w+j, c+1))

print(ans)