Problem:


Score : 400 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

1

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

Note that he cannot walk diagonally.

Sample Input 2

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

Sample Output 2

-1

He cannot move from there.

Sample Input 3

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

Sample Output 3

0

No use of magic is needed.

Sample Input 4

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

Sample Output 4

2



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


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
cy, cx = map(int, input().split())
dy, dx = map(int, input().split())
cx -= 1
cy -= 1
dx -= 1
dy -= 1

maze = []
for hh in range(H):
    maze.append(input())

stepx = [-1, 0, 1, 0]
stepy = [0, -1, 0, 1]
visited = [[0]*(W+2) for _ in range(H+2)]
def floodfill(comp, src):
    count = 0
    while len(src) > 0 and visited[dy][dx] <= 0:
        stak = []
        for (sy, sx) in src:
            #add to new component
            visited[sy][sx] = comp
            if sy == dy and sx == dx: break
            count += 1
            for i in range(4):
                ny, nx = sy + stepy[i], sx + stepx[i]
                if nx >= 0 and nx < W and ny >= 0 and ny < H\
                        and visited[ny][nx] == 0 and maze[ny][nx] == '.':
                    visited[ny][nx] = -1
                    stak.append((ny, nx))
        src = stak
    return count


def findnext(comp):
    count = 0
    nxt = []
    for h in range(0, H):
        for w in range(0, W):
            if visited[h][w] == comp:
                for ii in range(-2, 3):
                    nh = h + ii
                    if nh >= 0 and nh < H:
                        for jj in range(-2, 3):
                            nw = w + jj
                            if nw >= 0 and nw < W and visited[nh][nw] == 0 and maze[nh][nw] == '.':
                                visited[nh][nw] = -1
                                nxt.append((nh, nw))

    return nxt

ans = 0
total = 0
comp = 1

#floodfill source
if maze[cy][cx] == '.' and visited[cy][cx] == 0:
    count = floodfill(comp, [(cy, cx)])

# #floodfill dest
# if maze[dy][dx] == '.' and visited[dy][dx] == 0:
#     count = floodfill(comp, (dy, dx))
#     if count > 0:
#         total += count
#         comp += 1
#
#
while count > 0 and visited[dy][dx] <= 0:
    total += count
    src = findnext(comp)
    comp += 1
    if len(src) > 0:
        count = floodfill(comp, src)
    else: count = 0

print(visited[dy][dx] - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
import  math
from heapq import *
import fractions
import bisect
from collections import deque
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

INF=10**9
H,W=nm()
sx,sy=nm()
gx,gy=nm()
mass=[[0 for i in range(W)] for j in range(H)]
edge1=[[[] for i in range(W)] for j in range(H)]
edge2=[[[] for i in range(W)] for j in range(H)]

def bfs(start,edge1,edge2):
    d=[[INF for i in range(1000)] for j in range(1000)]
    d[start[0]][start[1]]=0
    q=deque([start])
    while (q):
        e=q.popleft()
        for i,j in edge1[e[0]][e[1]]:
            if(d[e[0]][e[1]]<d[i][j]):
                d[i][j]=d[e[0]][e[1]]
                q.appendleft((i,j))   
        for i,j in edge2[e[0]][e[1]]:
            if(d[e[0]][e[1]]+1<d[i][j]):
                d[i][j]=d[e[0]][e[1]]+1
                q.append((i,j))   
    return d

for i in range(H):
    t=list(ns())
    for j in range(W):
        if(t[j]=='.'):
            mass[i][j]=1

for i in range(H):
    for j in range(W):
        for k in range(-2,3):
            for l in range(-2,3):
                if((k==0 and l==0) or (i+k)<0 or (j+l)<0 or H<=(i+k) or W<=(j+l)):
                    continue
                else:
                    if(mass[i+k][j+l]==1):
                        if(abs(k)^2+abs(l)^2==1):
                            edge1[i][j].append((i+k,j+l))
                        else:
                            edge2[i][j].append((i+k,j+l))


start=[sx-1,sy-1]
d=bfs(start,edge1,edge2)
if(d[gx-1][gy-1]==INF):
    print(-1)
    sys.exit(0)
print(d[gx-1][gy-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
S = tuple(map(lambda x:int(x)-1, input().split()))
G = tuple(map(lambda x:int(x)-1, input().split()))
field = []
for _ in range(H):
    field.append(input())

q = deque()
q.append([S, 0])
pos2cost = {}

def can_go(pos):
    if pos[0] >= 0 and pos[0] < H and pos[1] >= 0 and pos[1] < W:
        if field[pos[0]][pos[1]] == '.':
            return True
        else:
            return False
    else:
        return False

def recursive_walk(pos):
    dests = set()
    stack = [pos]
    while stack:
        pos = stack.pop()
        if pos in dests:
            continue
        dests.add(pos)
        stack += walk(pos)
    return dests

def walk(pos):
    dests = []
    for d in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        new_pos = (pos[0]+d[0], pos[1]+d[1])
        if can_go(new_pos):
            dests.append(new_pos)
    return dests

def warp(pos):
    dests = []
    for dy in range(-2, 3):
        for dx in range(-2, 3):
            new_pos = (pos[0]+dy, pos[1]+dx)
            if can_go(new_pos):
                dests.append(new_pos)
    return dests

while q:
    pos, cost = q.popleft()
    if pos in pos2cost and pos2cost[pos] <= cost:
        continue
    pos2cost[pos] = cost
    if pos == G:
        break
    for dest in recursive_walk(pos):
        q.append((dest, cost))
    for dest in warp(pos):
        q.append((dest, cost+1))
if G in pos2cost:
    print(pos2cost[G])
else:
    print(-1)

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())
m=[input()for _ in[0]*h]
ch-=1;cw-=1;dh-=1;dw-=1;
dist=[[1e9]*w for _ in[0]*h]
dist[ch][cw]=0
from collections import deque
q=deque([(ch,cw)])
e=(-2,-1,0,1,2)
while len(q):
	i,j=q.popleft()
	d=dist[i][j]
	for ni,nj in ((i-1,j),(i,j-1),(i+1,j),(i,j+1)):
		if not(0<=ni<h and 0<=nj<w):continue
		if m[ni][nj]=='#':continue
		if dist[ni][nj]<=d:continue
		dist[ni][nj]=d
		p=(ni,nj)
		while q.count(p):q.remove(p)
		q.appendleft(p)
	for s in e:
		for t in e:
			ni,nj=i+s,j+t
			if not(0<=ni<h and 0<=nj<w):continue
			if m[ni][nj]=='#':continue
			if dist[ni][nj]<=d+1:continue
			dist[ni][nj]=d+1
			if q.count((ni,nj))==0:q.append((ni,nj))
r=dist[dh][dw]
print(r if r!=1e9 else-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def input(): return sys.stdin.readline().strip()

icase=0
if icase==0:
    h,w=map(int,input().split())
    ch,cw=map(int,input().split())
    ch-=1
    cw-=1
    dh,dw=map(int,input().split())
    dh-=1
    dw-=1
    s=[[] for i in range(h)]
    for i in range(h):
        s[i]=input()
        
ij=[(1,0),(-1,0),(0,1),(0,-1)]
wpij=[(1,1),(-1,-1),(-1,1),(1,-1),
      (2,-2),(2,-1),(2,0),(2,1),(2,2),
      (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),
      (1,2),(0,2),(-1,2),(1,-2),(0,-2),(-1,-2)]

hh=[i for i in range(h)]
ww=[i for i in range(w)]

g=[[[] for i in range(w)] for i in range(h)]
gg=[[[] for i in range(w)] for i in range(h)]
wpg2=[[0]*w for i in range(h)]
#wpg2=[[[] for i in range(w)] for i in range(h)]
wpg=[]

for i in hh:
    for j in ww:
        g[i][j]=[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]==".")]
#        wpg2[i][j]=[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]=="#")]
for i in hh:
    for j in ww:
        if i+1<h and s[i+1][j]=="#": wpg2[i][j]=1
        elif 0<=i-1 and s[i-1][j]=="#": wpg2[i][j]=1
        elif j+1<w and s[i][j+1]=="#": wpg2[i][j]=1
        elif 0<=j-1 and s[i][j-1]=="#": wpg2[i][j]=1
                
#        if (i+1<h and s[i+1][j]=="#") or \
#           (0<=i-1 and s[i-1][j]=="#") or \
#           (j+1<w and s[i][j+1]=="#") or \
#           (0<=j-1 and s[i][j-1]=="#"): 
#            wpg2[i][j]=1


#g=[[[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]==".")] for j in ww ] for i in hh]


#wpg2=[[[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]=="#")] for j in ww ] for i in hh]


for i in hh:
    for j in ww:
        if wpg2[i][j]>=1:
            wpg.append((i,j))
                
for i,j in wpg:
    for ii,jj in wpij:
         if 0<=i+ii and i+ii<h and 0<=j+jj \
            and j+jj<w and s[i+ii][j+jj]==".":
                gg[i][j].append((i+ii,j+jj))        

q=deque([(ch,cw)])
qq=deque()
parent=[[-1]*w for i in range(h)]
parent[ch][cw]=0
dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0
while True:
    while q:
#        print("q1:",q)
        hi,wi = q.popleft()
        if len(gg[hi][wi])>0:
            qq.append((hi,wi))
        for hj,wj in g[hi][wi]:
            if parent[hj][wj] !=-1:
                continue
            else:
                parent[hj][wj]=(hi,wi)
                dist[hj][wj]=dist[hi][wi]+1
                q.append((hj,wj))
                if hj==dh and wj==dw:
                    print(dist[dh][dw]//(10**7))   
                    sys.exit()

    while qq:
        hi,wi = qq.popleft()
        for hj,wj in gg[hi][wi]:
            if parent[hj][wj]!=-1:
                continue
            parent[hj][wj]=(hi,wi)
            dist[hj][wj]=dist[hi][wi]+10**7
            q.append((hj,wj))
            if hj==dh and wj==dw:
                print(dist[dh][dw]//(10**7))   
                sys.exit()

    if len(q)==0:
        break
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def input(): return sys.stdin.readline().strip()

icase=0
if icase==0:
    h,w=map(int,input().split())
    ch,cw=map(int,input().split())
    ch-=1
    cw-=1
    dh,dw=map(int,input().split())
    dh-=1
    dw-=1
    s=[[] for i in range(h)]
    for i in range(h):
        s[i]=input()
        
ij=[(1,0),(-1,0),(0,1),(0,-1)]
wpij=[(1,1),(-1,-1),(-1,1),(1,-1),
      (2,-2),(2,-1),(2,0),(2,1),(2,2),
      (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),
      (1,2),(0,2),(-1,2),(1,-2),(0,-2),(-1,-2)]

hh=[i for i in range(h)]
ww=[i for i in range(w)]

g=[[[] for i in range(w)] for i in range(h)]
gg=[[[] for i in range(w)] for i in range(h)]
wpg2=[[0]*w for i in range(h)]
#wpg2=[[[] for i in range(w)] for i in range(h)]
wpg=[]

for i in hh:
    for j in ww:
        g[i][j]=[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]==".")]
#        wpg2[i][j]=[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]=="#")]
#for i in hh:
#    for j in ww:
        if i+1<h and s[i+1][j]=="#": wpg2[i][j]=1
        elif 0<=i-1 and s[i-1][j]=="#": wpg2[i][j]=1
        elif j+1<w and s[i][j+1]=="#": wpg2[i][j]=1
        elif 0<=j-1 and s[i][j-1]=="#": wpg2[i][j]=1
                
#        if (i+1<h and s[i+1][j]=="#") or \
#           (0<=i-1 and s[i-1][j]=="#") or \
#           (j+1<w and s[i][j+1]=="#") or \
#           (0<=j-1 and s[i][j-1]=="#"): 
#            wpg2[i][j]=1


#g=[[[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]==".")] for j in ww ] for i in hh]


#wpg2=[[[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]=="#")] for j in ww ] for i in hh]


for i in hh:
    for j in ww:
        if wpg2[i][j]>=1:
            wpg.append((i,j))
                
for i,j in wpg:
    for ii,jj in wpij:
         if 0<=i+ii and i+ii<h and 0<=j+jj \
            and j+jj<w and s[i+ii][j+jj]==".":
                gg[i][j].append((i+ii,j+jj))        

q=deque([(ch,cw)])
qq=deque()
parent=[[-1]*w for i in range(h)]
parent[ch][cw]=0
dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0
while True:
    while q:
#        print("q1:",q)
        hi,wi = q.popleft()
        if len(gg[hi][wi])>0:
            qq.append((hi,wi))
        for hj,wj in g[hi][wi]:
            if parent[hj][wj] !=-1:
                continue
            else:
                parent[hj][wj]=(hi,wi)
                dist[hj][wj]=dist[hi][wi]+1
                q.append((hj,wj))
                if hj==dh and wj==dw:
                    print(dist[dh][dw]//(10**7))   
                    sys.exit()

    while qq:
        hi,wi = qq.popleft()
        for hj,wj in gg[hi][wi]:
            if parent[hj][wj]!=-1:
                continue
            parent[hj][wj]=(hi,wi)
            dist[hj][wj]=dist[hi][wi]+10**7
            q.append((hj,wj))
            if hj==dh and wj==dw:
                print(dist[dh][dw]//(10**7))   
                sys.exit()

    if len(q)==0:
        break
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import deque
h, w = map(int, stdin.readline().split())
ch, cw = map(int, stdin.readline().split())
dh, dw = map(int, stdin.readline().split())
grid = ''.join([stdin.readline()[:-1] for i in range(h)])

def pos(y, x):
    if 0 > y or 0 > x or h <= y or w <= x: return "x"
    return grid[y * w + x]
 
que_zero = deque()
que_one = deque()
que_zero.append((ch-1, cw-1, 0))
dist = [[10 ** 10] * w for i in range(h)]
dist[ch-1][cw-1] = 0
 
while len(que_zero) + len(que_one) > 0:
    y, x, cost = que_zero.popleft() if len(que_zero) > 0 else que_one.popleft()
    for i in range(-2, 3):
        for j in range(-2, 3):
            if i == 0 and j == 0: continue
            p = pos(y+i, x+j)
            if {i, j} != {1, 0} and {i, j} != {-1, 0}:
                if p == "." and dist[y+i][x+j] > cost + 1:
                    dist[y+i][x+j] = cost + 1
                    que_one.append((y+i, x+j, cost+1))
            elif p == "." and dist[y+i][x+j] > cost:
                dist[y+i][x+j] = cost
                que_zero.append((y+i, x+j, cost))
 
 
print(dist[dh-1][dw-1] if dist[dh-1][dw-1] != 10 ** 10 else -1)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import deque
h, w = map(int, stdin.readline().split())
ch, cw = map(int, stdin.readline().split())
dh, dw = map(int, stdin.readline().split())
grid = ''.join([stdin.readline()[:-1] for i in range(h)])

def pos(y, x):
    if 0 > y or 0 > x or h <= y or w <= x: return "x"
    return grid[y * w + x]

que = deque()
que.append((ch-1, cw-1, 0))
dist = [[10 ** 10] * w for i in range(h)]
dist[ch-1][cw-1] = 0

while len(que) > 0:
    y, x, cost = que.popleft()
    for i in range(-2, 3):
        for j in range(-2, 3):
            if i == 0 and j == 0: continue
            p = pos(y+i, x+j)
            tmp = 0
            if {i, j} != {1, 0} and {i, j} != {-1, 0}: tmp = 1
            if p == "." and dist[y+i][x+j] > cost + tmp:
                dist[y+i][x+j] = cost + tmp
                if tmp == 1: que.append((y+i, x+j, cost+1))
                else: que.appendleft((y+i, x+j, cost))
                

print(dist[dh-1][dw-1] if dist[dh-1][dw-1] != 10 ** 10 else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = [int(i) for i in input().split()]
ch, cw = [int(i) for i in input().split()]
dh, dw = [int(i) for i in input().split()]
grid = ''.join([input() for i in range(h)])

def pos(y, x):
    if 0 > y or 0 > x or h <= y or w <= x: return "x"
    return grid[y * w + x]

que = deque()
que.append((ch-1, cw-1, 0))
dist = [[10 ** 10] * w for i in range(h)]
dist[ch-1][cw-1] = 0

while len(que) > 0:
    y, x, cost = que.popleft()
    for i in range(-2, 3):
        for j in range(-2, 3):
            if i == 0 and j == 0: continue
            p = pos(y+i, x+j)
            tmp = 0
            if {i, j} != {1, 0} and {i, j} != {-1, 0}: tmp = 1
            if p == "." and dist[y+i][x+j] > cost + tmp:
                dist[y+i][x+j] = cost + tmp
                if tmp == 1: que.append((y+i, x+j, cost+1))
                else: que.appendleft((y+i, x+j, cost))
                

print(dist[dh-1][dw-1] if dist[dh-1][dw-1] != 10 ** 10 else -1)

Submission status: Time Limit Exceeded

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

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


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

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

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

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

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)

count = 0
while True:
    q_warp = SearchNum(T,count)
    count += 1
    if q_warp.empty():
        break
    
    while not q_warp.empty():
        n = q_warp.get()
        Warp([n[0],n[1]],T,count)
        
    for i in range(H + 4):
        for j in range(W + 4):
            if T[i][j] == count:
                BFS([i,j],T,count)

        
        
    if count > 2000:
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break


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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = [int(i) for i in input().split()]
ch, cw = [int(i) for i in input().split()]
dh, dw = [int(i) for i in input().split()]
grid = ''.join([input() for i in range(h)])

def pos(y, x):
    if 0 > y or 0 > x or h <= y or w <= x: return "x"
    return grid[y * w + x]

que_zero = deque()
que_one = deque()
que_zero.append((ch-1, cw-1, 0))
dist = [[10 ** 10] * w for i in range(h)]
dist[ch-1][cw-1] = 0

while len(que_zero) + len(que_one) > 0:
    y, x, cost = que_zero.popleft() if len(que_zero) > 0 else que_one.popleft()
    for i in range(-2, 3):
        for j in range(-2, 3):
            if i == 0 and j == 0: continue
            p = pos(y+i, x+j)
            if {i, j} != {1, 0} and {i, j} != {-1, 0}:
                if p == "." and dist[y+i][x+j] > cost + 1:
                    dist[y+i][x+j] = cost + 1
                    que_one.append((y+i, x+j, cost+1))
            elif p == "." and dist[y+i][x+j] > cost:
                dist[y+i][x+j] = cost
                que_zero.append((y+i, x+j, cost))


print(dist[dh-1][dw-1] if dist[dh-1][dw-1] != 10 ** 10 else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = [int(i) for i in input().split()]
ch, cw = [int(i) for i in input().split()]
dh, dw = [int(i) for i in input().split()]
grid = ''.join([input() for i in range(h)])

def pos(y, x):
    if 0 > y or 0 > x or h <= y or w <= x: return "x"
    return grid[y * w + x]

que_zero = deque()
que_one = deque()
que_zero.append((ch-1, cw-1, 0))
dist = [[10 ** 10] * w for i in range(h)]
dist[ch-1][cw-1] = 0

while len(que_zero) + len(que_one) > 0:
    y, x, cost = que_zero.popleft() if len(que_zero) > 0 else que_one.popleft()
    for i in range(-2, 3):
        for j in range(-2, 3):
            if i == 0 and j == 0: continue
            if {i, j} != {1, 0} and {i, j} != {-1, 0}:
                if pos(y+i, x+j) == "." and dist[y+i][x+j] > cost + 1:
                    dist[y+i][x+j] = cost + 1
                    que_one.append((y+i, x+j, cost+1))
            elif pos(y+i, x+j) == "." and dist[y+i][x+j] > cost:
                dist[y+i][x+j] = cost
                que_zero.append((y+i, x+j, cost))

print(dist[dh-1][dw-1] if dist[dh-1][dw-1] != 10 ** 10 else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = [int(i) for i in input().split()]
ch, cw = [int(i) for i in input().split()]
dh, dw = [int(i) for i in input().split()]
grid = ''.join([input() for i in range(h)])

def pos(y, x):
    if 0 > y or 0 > x or h <= y or w <= x: return "x"
    return grid[y * w + x]

que_zero = deque()
que_one = deque()
que_zero.append((ch-1, cw-1, 0))
dist = [[5 * (10 ** 16)] * w for i in range(h)]
dist[ch-1][cw-1] = 0

while len(que_zero) + len(que_one) > 0:
    y, x, cost = que_zero.popleft() if len(que_zero) > 0 else que_one.popleft()
    for i in range(-2, 3):
        for j in range(-2, 3):
            if i == 0 and j == 0: continue
            if {i, j} != {1, 0} and {i, j} != {-1, 0}:
                if pos(y+i, x+j) == "." and dist[y+i][x+j] > cost + 1:
                    dist[y+i][x+j] = cost + 1
                    que_one.append((y+i, x+j, cost+1))
            elif pos(y+i, x+j) == "." and dist[y+i][x+j] > cost:
                dist[y+i][x+j] = cost
                que_zero.append((y+i, x+j, cost))



            


print(dist[dh-1][dw-1] if dist[dh-1][dw-1] != 5 * (10 ** 16) else -1)

Submission status: Time Limit Exceeded

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

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


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

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

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

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

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)

count = 0
while True:
    q_warp = SearchNum(T,count)
    count += 1
    if q_warp.empty():
        break
    
    while not q_warp.empty():
        n = q_warp.get()
        Warp([n[0],n[1]],T,count)
        
    q_BFS = SearchNum(T,count)
    while not q_BFS.empty():
        n2 = q_BFS.get()
        BFS(n2,T,count)
        

    if T[D[0] + 2][D[1] + 2] != 9999:
        break


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

Submission status: Time Limit Exceeded

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

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


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

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

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

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

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            T[i+2][j+2] = -1
        if S[i][j] == '.':
            T[i+2][j+2] = 9999
                
T[C[0] + 2][C[1] + 2] = 0
BFS([C[0] + 2,C[1] + 2],T,0)

count = 0
while True:
    q_warp = SearchNum(T,count)
    count += 1
    if q_warp.empty():
        break
    
    while not q_warp.empty():
        n = q_warp.get()
        Warp([n[0],n[1]],T,count)
        
    q_BFS = SearchNum(T,count)
    while not q_BFS.empty():
        n2 = q_BFS.get()
        BFS(n2,T,count)
        
    if count > 2000:
        break
    if T[D[0] + 2][D[1] + 2] != 9999:
        break


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

Submission status: Time Limit Exceeded

Solution code:
import sys
import  math
from heapq import *
import fractions
import bisect
from collections import deque
stdin = sys.stdin
     
ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

INF=10**9
H,W=nm()
sx,sy=nm()
gx,gy=nm()
mass=[[0 for i in range(1000)] for j in range(1000)]
edge1=[[[] for i in range(1000)] for j in range(1000)]
edge2=[[[] for i in range(1000)] for j in range(1000)]

def bfs(start,edge1,edge2):
    d=[[INF for i in range(1000)] for j in range(1000)]
    d[start[0]][start[1]]=0
    q=deque([start])
    while (q):
        e=q.popleft()
        for i,j in edge1[e[0]][e[1]]:
            if(d[e[0]][e[1]]<d[i][j]):
                d[i][j]=d[e[0]][e[1]]
                q.appendleft((i,j))   
        for i,j in edge2[e[0]][e[1]]:
            if(d[e[0]][e[1]]+1<d[i][j]):
                d[i][j]=d[e[0]][e[1]]+1
                q.append((i,j))   
    return d

for i in range(H):
    t=list(ns())
    for j in range(W):
        if(t[j]=='.'):
            mass[i][j]=1

for i in range(H):
    for j in range(W):
        for k in range(-2,3):
            for l in range(-2,3):
                if((k==0 and l==0) or i+k<0 or j+l<0 or 999<(i+k) or 999<(j+l)):
                    continue
                else:
                    if(mass[i+k][j+l]==1):
                        if(abs(k)^2+abs(l)^2==1):
                            edge1[i][j].append((i+k,j+l))
                        else:
                            edge2[i][j].append((i+k,j+l))


start=[sx-1,sy-1]
d=bfs(start,edge1,edge2)
if(d[gx-1][gy-1]==INF):
    print(-1)
    sys.exit(0)
print(d[gx-1][gy-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def input(): return sys.stdin.readline().strip()

icase=0
if icase==0:
    h,w=map(int,input().split())
    ch,cw=map(int,input().split())
    ch-=1
    cw-=1
    dh,dw=map(int,input().split())
    dh-=1
    dw-=1
    s=[[] for i in range(h)]
    for i in range(h):
        s[i]=input()
        
ij=[(1,0),(-1,0),(0,1),(0,-1)]
wpij=[(1,1),(-1,-1),(-1,1),(1,-1),
      (2,-2),(2,-1),(2,0),(2,1),(2,2),
      (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),
      (1,2),(0,2),(-1,2),(1,-2),(0,-2),(-1,-2)]

hh=[i for i in range(h)]
ww=[i for i in range(w)]

g=[[[] for i in range(w)] for i in range(h)]
gg=[[[] for i in range(w)] for i in range(h)]
wpg2=[[[] for i in range(w)] for i in range(h)]
wpg=[]

for i in hh:
    for j in ww:
        g[i][j]=[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]==".")]
        wpg2[i][j]=[(i+ii,j+jj) for ii,jj in ij if (0<=(i+ii)<h and 0<=(j+jj)<w and s[i+ii][j+jj]=="#")]

for i in hh:
    for j in ww:
        if len(wpg2[i][j])>=1:
            wpg.append((i,j))
                
for i,j in wpg:
    for ii,jj in wpij:
         if 0<=i+ii and i+ii<h and 0<=j+jj \
            and j+jj<w and s[i+ii][j+jj]==".":
                gg[i][j].append((i+ii,j+jj))        

q=deque([(ch,cw)])
qq=deque()
parent=[[-1]*w for i in range(h)]
parent[ch][cw]=0
dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0
while True:
    while q:
#        print("q1:",q)
        hi,wi = q.popleft()
        if len(gg[hi][wi])>0:
            qq.append((hi,wi))
        for hj,wj in g[hi][wi]:
            if parent[hj][wj] !=-1:
                continue
            else:
                parent[hj][wj]=(hi,wi)
                dist[hj][wj]=dist[hi][wi]+1
                q.append((hj,wj))
                if hj==dh and wj==dw:
                    print(dist[dh][dw]//(10**7))   
                    sys.exit()

    while qq:
        hi,wi = qq.popleft()
        for hj,wj in gg[hi][wi]:
            if parent[hj][wj]!=-1:
                continue
            parent[hj][wj]=(hi,wi)
            dist[hj][wj]=dist[hi][wi]+10**7
            q.append((hj,wj))
            if hj==dh and wj==dw:
                print(dist[dh][dw]//(10**7))   
                sys.exit()

    if len(q)==0:
        break
print(-1)