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: Wrong Answer

Solution code:
H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
S = ""
for h in range(H):
    S += input()
    
G = [{} for i in range(H*W)]
INF = 10**18
for h in range(H):
    for w in range(W):
        now = h * W + w
        if now != "#":
            # left
            t = now - 1
            if  h * W <= t:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0
            # right
            t = now + 1
            if  h * W <= t < (h+1) * W:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0
            # up
            t = now - W
            if 0 <= t < H*W:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0
            # down
            t = now + W
            if 0 <= t < H*W:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
S = ""
for h in range(H):
    S += input()
    
G = [{} for i in range(H*W)]
INF = 10**18
for h in range(H):
    for w in range(W):
        now = h * W + w
        if now != "#":
            # left
            t = now - 1
            if  h * W <= t:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0
            # right
            t = now + 1
            if  h * W <= t < (h+1) * W:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0
            # up
            t = now - W
            if 0 <= t < H*W:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0
            # down
            t = now + W
            if 0 <= t < H*W:
                if S[t] == "#":
                    G[now][t] = INF
                else:
                    G[now][t] = 0
        
            # Warp
            for hh in range(-2, 3):
                t = (h+hh)*W + w
                #print(now)
                for i in range(-2, 3):
                    t_ = t + i
                    if 0<= t_ < H*W  and ((h+hh) * W <= t_ <(h+hh+1) * W):
                        if t_ != now and t_ not in G[now].keys() and S[t_] == ".":
                            G[now][t_] = 1

Submission status: Wrong Answer

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 j in ww:
    for i in hh[0:-1]:
#    if i+1<h:
        if s[i+1][j]==".":
            g[i][j].append((i+1,j))        
    for i in hh[1:]:
#    if 0<=i-1:
#    for j in ww:
        if s[i-1][j]==".":
            g[i][j].append((i-1,j))        
for i in hh:
    for j in ww[0:-1]:
#        if j+1<w:
        if s[i][j+1]==".":
            g[i][j].append((i,j+1))        
#for i in hh:
    for j in ww[1:]:
#        if 0<=j-1:
        if s[i][j-1]==".":
            g[i][j].append((i,j-1))        
print(-2)

#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: Wrong Answer

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])
cost = [[-1] * W for _ in range(H)]

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, c = q.popleft()
    if cost[pos[0]][pos[1]] != -1:
        continue
    cost[pos[0]][pos[1]] = c
    if pos == G:
        break
    for dest in recursive_walk(pos):
        if cost[dest[0]][dest[1]] == -1:
            q.append((dest, c))
    for dest in warp(pos):
        if cost[dest[0]][dest[1]] == -1:
            q.append((dest, c+1))
print(cost[G[0]][G[1]])

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = tuple(map(int, input().split()))

E = tuple(map(int, input().split()))


matrix = [[ c for c in input()] for _ in range(H)]
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
jump = [(x, y) for x in [-2, -1, 0, 1, 2] for y in [-2, -1, 0, 1, 2]]

q = [S]
q_idx = 0
jump_idx = 0
cost = 0
matrix[S[0]-1][S[1]-1] = cost

jump_point = {S}

while q_idx < len(q):
  if q[q_idx] == E:
    break
  while q_idx < len(q):
    d = q[q_idx]

    
    q_idx += 1

    for t in direct:
      x = d[1] - 1 + t[1]
      y = d[0] - 1 + t[0]
      if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
        matrix[y][x] = cost
        q.append((y+1, x+1))
        jump_point.add((y+1, x+1))
  
  cost += 1
  for d in jump_point:
    for t in jump:
      x = d[1] - 1 + t[1]
      y = d[0] - 1 + t[0]
      if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
        matrix[y][x] = cost
        q.append((y+1, x+1))
  jump_point.clear()

if matrix[E[0] -1][E[1] -1] == ".":
  print(-1)
else:
  print(matrix[E[0] -1][E[1] -1])

Submission status: Wrong Answer

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):
        if dest not in pos2cost or pos2cost[dest] > cost:
            q.append((dest, cost+1))
    for dest in warp(pos):
        if dest not in pos2cost or pos2cost[dest] > cost+1:
            q.append((dest, cost+1))
if G in pos2cost:
    print(pos2cost[G])
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = tuple(map(int, input().split()))

E = tuple(map(int, input().split()))


matrix = [[ c for c in input()] for _ in range(H)]
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
jump = [(x, y) for x in [-2, -1, 0, 1, 2] for y in [-2, -1, 0, 1, 2]]

q = []
q_idx = 0
cost = 0
q.append(S)
matrix[S[0]-1][S[1]-1] = cost

jump_point = set()

while q_idx < len(q):
  if q[q_idx] == E:
    break
  while q_idx < len(q):
    d = q[q_idx]

    
    q_idx += 1

    for t in direct:
      x = d[1] - 1 + t[1]
      y = d[0] - 1 + t[0]
      if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
        matrix[y][x] = cost
        q.append((y+1, x+1))
        jump_point.add((y+1, x+1))
  
  cost += 1
  for d in jump_point:
    for t in jump:
      x = d[1] - 1 + t[1]
      y = d[0] - 1 + t[0]
      if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
        matrix[y][x] = cost
        q.append((y+1, x+1))
  jump_point.clear()

if matrix[E[0] -1][E[1] -1] == ".":
  print(-1)
else:
  print(matrix[E[0] -1][E[1] -1])

Submission status: Wrong Answer

Solution code:
import sys

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


def search_nearby(h, w):
  # 上下左右に隣接するマスを探索
	search(h + 1, w)
	search(h - 1, w)
	search(h, w + 1)
	search(h, w - 1)


def search(h, w):
	global que
	global next_que

	if can_reach(h, w):
		que.append([h, w])
		next_que.append([h, w])


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

	if h < 0 or h >= H or w < 0 or w >= W:
		return False
	elif maze[h][w] == '#':
		return False
	elif is_reached[h][w]:
		return False
	else:
		return True


def search_using_warp(h, w):
  # ワープ魔法で移動できるマスを探索
  for i in range(-2, 3):
    search(h - 2, w + i)
    search(h + 2, w + i)

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

  search(h, w + 2)
  search(h, w - 2)


from collections import deque
import copy

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

maze = []

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

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

next_que = deque()
next_que.append([Ch, Cw])
mp = 0

while len(next_que) > 0:
  que = copy.deepcopy(next_que)

	# コストiで到達可能なマスを列挙
  while len(que) > 0:
    h, w = que.popleft()
    is_reached[h][w] = True

    search_nearby(h, w)

  if is_reached[Dh][Dw]:
    print(mp)
    exit()

  que = copy.deepcopy(next_que)
  next_que.clear()
  mp += 1

	# コストiで到達可能なマスを列挙
  while len(que) > 0:
    h, w = que.popleft()
    is_reached[h][w] = True

    search_using_warp(h, w)

  if is_reached[Dh][Dw]:
    print(mp)
    exit()

print(-1)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = tuple(map(int, input().split()))

E = tuple(map(int, input().split()))


matrix = [[ c for c in input()] for _ in range(H)]
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
jump = [(x, y) for x in [-2, -1, 0, 1, 2] for y in [-2, -1, 0, 1, 2]]

q = []
q_idx = 0
cost = 0
q.append(S)
matrix[S[0]-1][S[1]-1] = cost


while q_idx < len(q):
  while q_idx < len(q):
    d = q[q_idx]

    
    q_idx += 1

    for t in direct:
      x = d[1] - 1 + t[1]
      y = d[0] - 1 + t[0]
      if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
        matrix[y][x] = cost
        q.append((y+1, x+1))
  
  cost += 1
  for t in jump:
    x = d[1] - 1 + t[1]
    y = d[0] - 1 + t[0]
    if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
      matrix[y][x] = cost
      q.append((y+1, x+1))

if matrix[E[0] -1][E[1] -1] == ".":
  print(-1)
else:
  print(matrix[E[0] -1][E[1] -1])

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = tuple(map(int, input().split()))

E = tuple(map(int, input().split()))


matrix = [[ c for c in input()] for _ in range(H)]
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
jump = [(x, y) for x in [-2, -1, 0, 1, 2] for y in [-2, -1, 0, 1, 2]]

q = []
q_idx = 0
cost = 0
q.append(S)
matrix[S[0]-1][S[1]-1] = cost


while q_idx < len(q):
  while q_idx < len(q):
    d = q[q_idx]

    
    q_idx += 1

    for t in direct:
      x = d[1] - 1 + t[1]
      y = d[0] - 1 + t[0]
      if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
        matrix[y][x] = cost
        q.append((y+1, x+1))
  
  cost += 1
  for t in jump:
    x = d[1] - 1 + t[1]
    y = d[0] - 1 + t[0]
    if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
      matrix[y][x] = cost
      q.append((y+1, x+1))

if matrix[E[0] -1][E[1] -1] == ".":
  print(-1)
else:
  print(matrix[E[0] -1][E[1] -1])
print(S)
print(E)
print(matrix)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = tuple(map(int, input().split()))

E = tuple(map(int, input().split()))


matrix = [[ c for c in input()] for _ in range(H)]
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
jump = [(x, y) for x in [-2, -1, 0, 1, 2] for y in [-2, -1, 0, 1, 2]]

q = []
q_idx = 0
cost = 0
q.append(S)
matrix[S[1]-1][S[0]-1] = cost


while q_idx < len(q):
  while q_idx < len(q):
    d = q[q_idx]

    
    q_idx += 1

    for t in direct:
      x = d[1] - 1 + t[1]
      y = d[0] - 1 + t[0]
      if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
        matrix[y][x] = cost
        q.append((y+1, x+1))
  
  cost += 1
  for t in jump:
    x = d[1] - 1 + t[1]
    y = d[0] - 1 + t[0]
    if 0 <= x < W and 0 <= y < H and matrix[y][x] == ".":
      matrix[y][x] = cost
      q.append((y+1, x+1))

if matrix[E[0] -1][E[1] -1] == ".":
  print(-1)
else:
  print(matrix[E[0] -1][E[1] -1])

Submission status: Wrong Answer

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 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
		q.appendleft((ni,nj))
	if not q:
		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
				q.append((ni,nj))
r=dist[dh][dw]
print(r if r!=1e9 else-1)

Submission status: Wrong Answer

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):
        if dest not in pos2cost or pos2cost[dest] > cost:
            q.append((dest, cost))
    for dest in warp(pos):
        if dest not in pos2cost or pos2cost[dest] > cost+1:
            q.append((dest, cost+1))
if G in pos2cost:
    print(pos2cost[G])
else:
    print(-1)

Submission status: Wrong Answer

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 j in ww:
    for i in hh[0:-2]:
#    if i+1<h:
        if s[i+1][j]==".":
            g[i][j].append((i+1,j))        
    for i in hh[1:]:
#    if 0<=i-1:
#    for j in ww:
        if s[i-1][j]==".":
            g[i][j].append((i-1,j))        
for i in hh:
    for j in ww[0:-2]:
#        if j+1<w:
        if s[i][j+1]==".":
            g[i][j].append((i,j+1))        
#for i in hh:
    for j in ww[1:]:
#        if 0<=j-1:
        if s[i][j-1]==".":
            g[i][j].append((i,j-1))        


#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: Wrong Answer

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: Wrong Answer

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]=="#")]
print(-2)
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: Wrong Answer

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 count > 1500:
        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)            

print(T)

Submission status: Wrong Answer

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):
    q = queue.Queue()
    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
                q.put([i,j])
    return q
    
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()
        q_BFS = Warp([n[0],n[1]],T,count)
        while not q_BFS.empty():
            n2 = q_BFS.get()
            BFS(n2,T,count)

    if count > 1500:
        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)            

print(T)