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:
import sys
input=sys.stdin.readline
import heapq
xy=[(1,0),(-1,0),(0,1),(0,-1)]
wp=[(-1,-1),(-1,1),(1,1),(1,-1),(2,0),(-2,0),(0,2),(0,-2),(-2,-1),(-2,1),(2,1),(2,-1),(-1,-2),(-1,2),(1,2),(1,-2),(-2,-2),(-2,2),(2,2),(2,-2)]

h,w=map(int,input().split())
c1,c2=map(int,input().split())
d1,d2=map(int,input().split())
d=[list(input().rstrip()) for i in range(h)]
d[c1-1][c2-1]=0
p=[]
if h==w==1000:
    print(-1)
    exit()
heapq.heappush(p,(0,c1-1,c2-1))
while len(p):
    a,b,c=heapq.heappop(p)
    for x,y in xy:
        x+=b
        y+=c
        if 0<=x<h and 0<=y<w and d[x][y]!="#":
            if d[x][y]=="." or d[x][y]>a:
                d[x][y]=a
                heapq.heappush(p,(a,x,y))
    for x,y in wp:
        x+=b
        y+=c
        if 0<=x<h and 0<=y<w and d[x][y]!="#":
            if d[x][y]=="." or d[x][y]>a+1:
                d[x][y]=a+1
                heapq.heappush(p,(a+1,x,y))
#    if len(p)>2000:
#        print(-1)
#    print(p)
#    if d[d1-1][d2-1]==a:
#        print(a)
#        exit()
#    print(p)
#    print(d)

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

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = [int(_) for _ in input().split()]
C = [int(_) - 1 for _ in input().split()]
D = [int(_) - 1 for _ in input().split()]

S = [input() for _ in range(H)]
V = [[-1 for w in range(W)] for h in range(H)]
F = [[False for w in range(W)] for h in range(H)]

V[C[0]][C[1]] = 0

pool = deque()
pool.append(tuple([0, C[0], C[1]]))
while(pool):
    c, y, x = pool.pop()
    if F[y][x]:
        continue
    F[y][x] = True
    for dx in [-2, -1, 0, 1, 2]:
        for dy in [-2, -1, 0, 1, 2]:
            if y + dy < 0 or H <= y + dy:
                continue
            if x + dx < 0 or W <= x + dx:
                continue
            if S[y+dy][x+dx] == "#":
                continue
            if c != V[y][x]:
                continue
            if (dx, dy) in [(-1,0),(1,0),(0,-1),(0,1)]:
                if V[y+dy][x+dx] == -1 or V[y+dy][x+dx] > V[y][x]:
                    V[y+dy][x+dx] = V[y][x]
                    pool.appendleft((c, y+dy, x+dx))
            elif V[y+dy][x+dx] == -1 or V[y+dy][x+dx] > V[y][x] + 1:
                V[y+dy][x+dx] = V[y][x] + 1
                pool.append((c+1, y+dy, x+dx))
print(V[D[0]][D[1]])

Submission status: Wrong Answer

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    from collections import deque

    h, w = map(int, readline().split())
    sr, sc = map(int, readline().split())
    gr, gc = map(int, readline().split())

    grid = [["#"] * (w + 2)]
    for _ in range(h):
        s = ["#"] + list(input()) + ["#"]
        grid.append(s)
    grid.append(["#"] * (w + 2))

    ans = 0
    que1 = deque()
    que1.append((sr, sc, 0))
    grid[sr][sc] = "!"

    while que1:
        cr, cc, cost = que1.popleft()
        if grid[cr][cc] == "!":
            continue
        if cr == gr and cc == gc:
            return print(cost)

        if grid[cr + 1][cc] == ".":
            que1.appendleft((cr + 1, cc, cost))
            grid[cr + 1][cc] = "!"
        if grid[cr - 1][cc] == ".":
            que1.appendleft((cr - 1, cc, cost))
            grid[cr - 1][cc] = "!"
        if grid[cr][cc + 1] == ".":
            que1.appendleft((cr, cc + 1, cost))
            grid[cr][cc + 1] = "!"
        if grid[cr][cc - 1] == ".":
            que1.appendleft((cr, cc - 1, cost))
            grid[cr][cc - 1] = "!"

        for mr in range(-2, 3):
            for mc in range(-2, 3):
                nr = cr + mr
                nc = cc + mc
                if 1 <= nr <= h and 1 <= nc <= w:
                    if grid[nr][nc] == ".":
                        que1.append((nr, nc, cost + 1))

    return print(-1)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

def p(arr):
	print("_______________________")
	for i in arr:
		for j in i:
			print(j,end=" ")
		print()

h,w = readInts()
ch,cw = readInts()
dh,dw = readInts()
s = [["#" for i in range(w+2)]]+[["#"]+ list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]

q = deque()
visited = [[-1]*(w+2) for i in range(h+2)]
count = (w+2)*(h+2)
for i in range(h+2):
	for j in range(w+2):
		if s[i][j]=="#":
			visited[i][j] = float("inf")
			count -= 1

from pprint import pprint
visited[ch][cw] = 0

q = {(ch,cw)}
set_list = set()
cost = 0
while count:
	while len(q) !=0:
		x,y = q.pop()
		set_list.add((x,y))
		visited[x][y] = cost
		count-=1
		if s[x-1][y]=="." and visited[x-1][y]==-1:
			q.add((x-1,y))
		if s[x][y-1]=="." and visited[x][y-1]==-1:
			q.add((x,y-1))
		if s[x+1][y]=="." and visited[x+1][y]==-1:
			q.add((x+1,y))
		if s[x][y+1]=="." and visited[x][y+1]==-1:
			q.add((x,y+1))

	if len(set_list)==0:
		exit()

	cost+=1
	while len(set_list) != 0:
		x,y = set_list.pop()
		for dx in range(-2,3):
			for dy in range(-2,3):
				x2 = x+dx
				y2 = y+dy
				if visited[min(x2,h+1)][min(y2,w+1)]!=-1: continue
				q.add((x2,y2))

print(visited[dh][dw])

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

def p(arr):
	print("_______________________")
	for i in arr:
		for j in i:
			print(j,end=" ")
		print()

h,w = readInts()
ch,cw = readInts()
dh,dw = readInts()
s = [["#" for i in range(w+2)]]+[["#"]+ list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]

q = deque()
visited = [[-1]*(w+2) for i in range(h+2)]
count = (w+2)*(h+2)
for i in range(h+2):
	for j in range(w+2):
		if s[i][j]=="#":
			visited[i][j] = float("inf")
			count -= 1

from pprint import pprint
visited[ch][cw] = 0

q = {(ch,cw)}
set_list = set()
cost = 0
while count:
	while len(q) !=0:
		x,y = q.pop()
		set_list.add((x,y))
		visited[x][y] = cost
		count-=1
		if s[x-1][y]=="." and visited[x-1][y]==-1:
			q.add((x-1,y))
		if s[x][y-1]=="." and visited[x][y-1]==-1:
			q.add((x,y-1))
		if s[x+1][y]=="." and visited[x+1][y]==-1:
			q.add((x+1,y))
		if s[x][y+1]=="." and visited[x][y+1]==-1:
			q.add((x,y+1))

	if len(set_list)==0:
		print(-1)
		exit()

	cost+=1
	while len(set_list) != 0:
		x,y = set_list.pop()
		for dx in range(-2,3):
			for dy in range(-2,3):
				x2 = x+dx
				y2 = y+dy
				if visited[min(x2,h+1)][min(y2,w+1)]!=-1: continue
				q.add((x2,y2))

print(visited[dh][dw])

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
H, W = map(int, input().split())
c = [int(i) + 1 for i in input().split()]
d = [int(i) + 1 for i in input().split()]

s = []
s.append('#'*(W+4))
s.append('#'*(W+4))
for i in range(H):
    a = input()
    s.append('##' + a + '##')
s.append('#'*(W+4))
s.append('#'*(W+4))

q = deque([]) # 探索開始点
qq = deque([])
q.append((c[0], c[1], 0))
visited = [[False for __ in range(W+4)] for _ in range(H+4)]

while q:
    xx, yy, kaisuu = q.popleft()
    if visited[xx][yy] == True:
        continue
    qq.append((xx, yy))
    ls = deque()
    while qq:
        x, y = qq.pop()
        visited[x][y] = True
        ls.append((x, y, kaisuu))
        if x == d[0] and y == d[1]:
            print(kaisuu)
            sys.exit()
        if s[x+1][y] == '.' and visited[x+1][y] == False:
            qq.append((x+1, y))
        if s[x-1][y] == '.' and visited[x-1][y] == False:
            qq.append((x-1, y))
        if s[x][y+1] == '.' and visited[x][y+1] == False:
            qq.append((x, y+1))
        if s[x][y-1] == '.' and visited[x][y-1] == False:
            qq.append((x, y-1))
    for u in ls:
        a, b, e = u
        for i in range(-2, 3):
            for j in range(-2, 3):
                if i == 0 and j == 0:
                    continue
                if abs(i) == 1 and abs(j) == 1:
                    continue
                if s[a+i][b+j] == '.' and visited[a+i][b+j] == False:
                    q.append((a+i, b+j, e+1))
print(-1)

Submission status: Wrong Answer

Solution code:
import heapq
xy=[(1,0),(-1,0),(0,1),(0,-1)]
wp=[(-1,-1),(-1,1),(1,1),(1,-1),(2,0),(-2,0),(0,2),(0,-2),(-2,-1),(-2,1),(2,1),(2,-1),(-1,-2),(-1,2),(1,2),(1,-2),(-2,-2),(-2,2),(2,2),(2,-2)]

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

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

Submission status: Wrong Answer

Solution code:
from sys import stdin
from collections import deque, defaultdict

readline = stdin.readline

def main():
    H, W = map(int, readline().rstrip().split())
    CH, CW = map(int, readline().rstrip().split())
    DH, DW = map(int, readline().rstrip().split())
    S = [list(readline().rstrip()) for _ in range(H)]
    v = defaultdict(lambda : False)
    dq = deque([(0, CH - 1, CW - 1)])
    while dq:
        c, h, w = dq.popleft()
        # print(f'{c} : {h} : {w} : {S[h][w]}')
        if (h, w) == (DH - 1, DW - 1):
            print(c)
            exit()
        if v[(h, w)]:
            continue
        v[(h, w)] = True
        for mh, mw in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                nh = mh + h
                nw = mw + w
                if H <= nh or nh < 0 or W <= nw or nw < 0:
                    continue
                if S[nh][nw] == '.' and not v[(nh, nw)]:
                    dq.appendleft([c, nh, nw])
        for mh in range(-2, 3):
            for mw in range(-2, 3):
                if h == w == 0:
                    continue
                nh = mh + h
                nw = mw + w
                if H <= nh or nh < 0 or W <= nw or nw < 0:
                    continue 
                if S[nh][nw] == '.' and not v[(nh, nw)]:
                    dq.append([c + 1, nh, nw])
    print(-1)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
H, W = map(int, input().split())
c = [int(i) + 1 for i in input().split()]
d = [int(i) + 1 for i in input().split()]

s = []
s.append('#'*(W+4))
s.append('#'*(W+4))
for i in range(H):
    a = input()
    s.append('##' + a + '##')
s.append('#'*(W+4))
s.append('#'*(W+4))

q = deque([]) # 探索開始点
qq = deque([])
q.append((c[0], c[1], 0))
visited = [[False for __ in range(W+4)] for _ in range(H+4)]

while q:
    xx, yy, kaisuu = q.popleft()
    if visited[xx][yy] == True:
        continue
    qq.append((xx, yy, kaisuu))
    ls = deque()
    while qq:
        x, y, kaisuu = qq.pop()
        visited[x][y] = True
        ls.append((x, y, kaisuu))
        if x == d[0] and y == d[1]:
            print(kaisuu)
            sys.exit()
        if s[x+1][y] == '.' and visited[x+1][y] == False:
            qq.append((x+1, y, kaisuu))
        if s[x-1][y] == '.' and visited[x-1][y] == False:
            qq.append((x-1, y, kaisuu))
        if s[x][y+1] == '.' and visited[x][y+1] == False:
            qq.append((x, y+1, kaisuu))
        if s[x][y-1] == '.' and visited[x][y-1] == False:
            qq.append((x, y-1, kaisuu))
    for u in ls:
        a, b, e = u
        for i in range(-2, 3):
            for j in range(-2, 3):
                if i == 0 and j == 0:
                    continue
                if abs(i) == 1 and abs(j) == 1:
                    continue
                if s[a+i][b+j] == '.' and visited[a+i][b+j] == False:
                    q.append((a+i, b+j, e+1))
print(-1)

Submission status: Wrong Answer

Solution code:
import heapq
xy=[(1,0),(-1,0),(0,1),(0,-1)]
wp=[(-1,-1),(-1,1),(1,1),(1,-1),(2,0),(-2,0),(0,2),(0,-2),(-2,-1),(-2,1),(2,1),(2,-1),(-1,-2),(-1,2),(1,2),(1,-2),(-2,-2),(-2,2),(2,2),(2,-2)]

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

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

Submission status: Wrong Answer

Solution code:
# Date [ 2020-08-22 21:07:07 ]
# Problem [ d.py ]
# Author Koki_tkg

#これで通らなかったらDijkstraで解く

import sys;      from decimal import Decimal
import math;     from itertools import combinations, product
import bisect;   from collections import Counter, deque, defaultdict

# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846

def read_str():      return sys.stdin.readline().strip()
def read_int():      return int(sys.stdin.readline().strip())
def read_ints():     return map(int, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def lcm(a: int, b: int) -> int: return (a * b) // math.gcd(a, b)

def Main():
    H, W = read_ints()
    wiz = read_int_list()
    goal = read_int_list()
    grid = [read_str() for _ in range(H)]
    dist = [[0] * W for _ in range(H)]
    
    dist[wiz[0] - 1][wiz[1] - 1] = 1
    dist[goal[0] - 1][goal[1] - 1] = -10
    
    que = deque([[wiz[0] - 1, wiz[1] - 1]])
    que2 = deque()

    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    dx8 = [0, 1, 2, 2, 2, 2, 2, 1, 0, -1, -2, -2, -2, -2, -2, -1]
    dy8 = [2, 2, 2, 1, 0, -1, -2, -2, -2, -2, -2, -1, 0, 1, 2, 2]
    cnt = 0

    while que or que2:
        while que:
            y, x = que.popleft()

            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]
                
                if nx < 0 or nx >= W or ny < 0 or ny >= H:
                    continue

                if dist[ny][nx] == -10:
                    print(cnt)
                    sys.exit()

                if grid[ny][nx] == '#' and dist[y][x] == 1:
                    que2.append([y, x])
                    dist[y][x] = 2
                    continue                
                
                if dist[ny][nx] != 0 or grid[ny][nx] == '#':
                    continue
            
                que.append([ny, nx])
                dist[ny][nx] = 1
        
        cnt += 1
        while que2:
            y, x = que2.popleft()
            
            for i in range(16):
                nx = x + dx8[i]
                ny = y + dy8[i]

                if nx < 0 or nx >= W or ny < 0 or ny >= H:
                    continue
                
                if dist[ny][nx] == -10:
                    print(cnt)
                    sys.exit()
                
                if dist[ny][nx] != 0 or grid[ny][nx] == '#':
                    continue
        
                que.append([ny, nx])
                dist[ny][nx] = 1

    print(-1)


if __name__ ==  '__main__':
    Main()

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")

import numpy as np
from numba import njit, b1, i4, i8, f8
from heapq import heappop as hpp, heappush as hp

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
rows,cols = h,w

OK = "."
NG = "#"

ss = np.array([[c=="#" for c in input()] for _ in range(h)])
inf = 1<<30

@njit((b1[:, :], i8, i8, i8, i8, i8, i8), cache=True)
def main(ss,ch,cw,dh,dw,h,w):
    start = (ch,cw)
    goal = (dh,dw)
    n = h * w
    seen = np.full(n, inf, np.int64)
    seen[ch*w+cw] = 0
    q = [(0, start, start)] # ワープ回数, 最後の道の位置
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    while q:
        pnum,(ux,uy),pprv = hpp(q)
    #     print(ux,uy, num, prv)
        for xx,yy in zip(dx,dy):
            x = ux+xx
            y = uy+yy
            num = pnum
            prv = pprv
            if x<0 or y<0 or x>=h or y>=w:
                continue
            if abs(x-prv[0])>=3 or abs(y-prv[1])>=3:
                continue

            if not ss[x][y]:
                prv = (x,y)
            else:
                if abs(x-prv[0]) + abs(y-prv[1]) == 1:
                    prv = (ux,uy)
                    num += 1

            if seen[x*w+y]>num:
                seen[x*w+y] = num
                hp(q, (num, (x,y), prv))
    val = seen[goal[0]*w+goal[1]]
#     print(seen)
    if val==inf:
        return -1
    else:
        return val
print(main(ss,ch,cw,dh,dw,h,w))

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

res_S = [[-1]*W for i in range(H)]
dx = [1,-1,0,0,0]
ddx = [-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,0,1,2]
dy = [0,0,0,1,-1]
ddy = [-2,-2,-2,-2,-2,-1,-1,-1,-1,-1,0,0,0,0,0,1,1,1,1,1,2,2,2,2,2]
count = 0

que = [(Ch,Cw)]
que_warp =[(Ch,Cw)]
res_S[Ch-1][Cw-1] = 0

while (que or que_warp):
    for i in range(len(que)):
        que_warp.append(que[i])
    while (que):
        for i in range(4):
            nx = int(que[0][0]+dx[i])
            ny = int(que[0][1]+dy[i])
            if (1<=nx<=H) and (1<=ny<=W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1]=count
                    que.append((nx,ny))
                    que_warp.append((nx,ny))
        que.pop(0)

    count += 1

    while(que_warp):
        for i in range(len(ddx)):
            nx = int(que_warp[0][0] + ddx[i])
            ny = int(que_warp[0][1] + ddy[i])
            if (1 <= nx <= H) and (1 <= ny <= W):
                if res_S[nx-1][ny-1]<0 and S[nx-1][ny-1]=='.':
                    res_S[nx-1][ny-1] = count
                    que.append((nx, ny))
        que_warp.pop(0)

print (res_S[Dh-1][Dw-1])

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")

import numpy as np
from numba import njit, b1, i4, i8, f8
from heapq import heappop as hpp, heappush as hp

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
rows,cols = h,w

OK = "."
NG = "#"

ss = np.array([[c=="#" for c in input()] for _ in range(h)])
inf = 1<<30

@njit((b1[:, :], i8, i8, i8, i8, i8, i8), cache=True)
def main(ss,ch,cw,dh,dw,h,w):
    start = (ch,cw)
    goal = (dh,dw)
    n = h * w
    seen = np.full(n, inf, np.int64)
    seen[ch*w+cw] = 0
    q = [(start, 0, start)] # ワープ回数, 最後の道の位置
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    while q:
        (ux,uy),pnum,pprv = hpp(q)
    #     print(ux,uy, num, prv)
        for xx,yy in zip(dx,dy):
            x = ux+xx
            y = uy+yy
            num = pnum
            prv = pprv
            if x<0 or y<0 or x>=h or y>=w:
                continue
            if abs(x-prv[0])>=3 or abs(y-prv[1])>=3:
                continue

            if not ss[x][y]:
                prv = (x,y)
            else:
                if abs(x-prv[0]) + abs(y-prv[1]) == 1:
                    prv = (ux,uy)
                    num += 1

            if seen[x*w+y]>num:
                seen[x*w+y] = num
                hp(q, ((x,y), num, prv))
    val = seen[goal[0]*w+goal[1]]
#     print(seen)
    if val==inf:
        return -1
    else:
        return val
print(main(ss,ch,cw,dh,dw,h,w))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h, w = LI()
ch, cw = LI()
dh, dw = LI()
s = [input() for _ in range(h)]

dx, dy = [1, 0, -1, 0, 1, -1, -1, 1], [0, 1, 0, -1, 1, 1, -1, -1]
que = deque([(cw-1, ch-1)])
d = [[10**10] * w for _ in range(h)]
d[ch-1][cw-1] = 0
while que:
    x, y = que.popleft()
    for i in range(8):
        nx, ny = x + dx[i], y + dy[i]
        if 0 <= nx < w and 0 <= ny < h:
            if i <= 3 and s[ny][nx] == '.' and d[ny][nx] > d[y][x]:
                d[ny][nx] = d[y][x]
                que.appendleft((nx, ny))
            elif s[ny][nx] == '#' and s[y][x] == '.' and d[ny][nx] > d[y][x] + 1:
                d[ny][nx] = d[y][x] + 1
                que.append((nx, ny))

if d[dh-1][dw-1] == 10**10:
    print(-1)
else:
    print(d[dh-1][dw-1])

Submission status: Wrong Answer

Solution code:
# Date [ 2020-08-22 21:07:07 ]
# Problem [ d.py ]
# Author Koki_tkg

import sys;      from decimal import Decimal
import math;     from itertools import combinations, product
import bisect;   from collections import Counter, deque, defaultdict

# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846

def read_str():      return sys.stdin.readline().strip()
def read_int():      return int(sys.stdin.readline().strip())
def read_ints():     return map(int, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def lcm(a: int, b: int) -> int: return (a * b) // math.gcd(a, b)

def Main():
    H, W = read_ints()
    wiz = read_int_list()
    goal = read_int_list()
    grid = [read_str() for _ in range(H)]
    dist = [[0] * W for _ in range(H)]
    
    dist[wiz[0] - 1][wiz[1] - 1] = 1
    dist[goal[0] - 1][goal[1] - 1] = -10
    
    que = deque([[wiz[0] - 1, wiz[1] - 1]])

    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    dx8 = [0, 1, 2, 2, 2, 2, 2, 1, 0, -1, -2, -2, -2, -2, -2, -1]
    dy8 = [2, 2, 2, 1, 0, -1, -2, -2, -2, -2, -2, -1, 0, 1, 2, 2]
    cnt = 0

    while que or que2:
        que2 = deque()
        while que:
            y, x = que.popleft()

            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]
                
                if nx < 0 or nx >= W or ny < 0 or ny >= H:
                    continue

                if dist[ny][nx] == -10:
                    print(cnt)
                    sys.exit()

                if grid[ny][nx] == '#' and dist[y][x] == 1:
                    que2.append([y, x])
                    dist[y][x] = 2
                    continue                
                
                if dist[ny][nx] != 0 or grid[ny][nx] == '#':
                    continue
            
                que.append([ny, nx])
                dist[ny][nx] = 1
        
        cnt += 1
        while que2:
            y, x = que2.popleft()
            
            for i in range(16):
                nx = x + dx8[i]
                ny = y + dy8[i]

                if nx < 0 or nx >= W or ny < 0 or ny >= H:
                    continue
                
                if dist[ny][nx] == -10:
                    print(cnt)
                    sys.exit()
                
                if dist[ny][nx] != 0 or grid[ny][nx] == '#':
                    continue
        
                que.append([ny, nx])
                dist[ny][nx] = 1

    print(-1)


if __name__ ==  '__main__':
    Main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from collections import deque
from collections import Counter
import math

def readInt():
	return int(input())
def readInts():
	return list(map(int, input().split()))
def readChar():
	return input()
def readChars():
	return input().split()

def p(arr):
	print("_______________________")
	for i in arr:
		for j in i:
			print(j,end=" ")
		print()

h,w = readInts()
ch,cw = readInts()
dh,dw = readInts()
s = [["#" for i in range(w+2)]]+[["#"]+ list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]

q = deque()
visited = [[-1]*(w+2) for i in range(h+2)]
count = (w+2)*(h+2)
for i in range(h+2):
	for j in range(w+2):
		if s[i][j]=="#":
			visited[i][j] = float("inf")
			count -= 1

from pprint import pprint
visited[ch][cw] = 0

q = {(ch,cw)}
set_list = set()
cost = 0
while count:
	while len(q) !=0:
		x,y = q.pop()
		set_list.add((x,y))
		visited[x][y] = cost
		count-=1
		if s[x-1][y]=="." and visited[x-1][y]==-1:
			q.add((x-1,y))
		if s[x][y-1]=="." and visited[x][y-1]==-1:
			q.add((x,y-1))
		if s[x+1][y]=="." and visited[x+1][y]==-1:
			q.add((x+1,y))
		if s[x][y+1]=="." and visited[x][y+1]==-1:
			q.add((x,y+1))

	if len(set_list)==0:
		print(-1)
		exit()

	cost+=1
	while len(set_list) != 0:
		x,y = set_list.pop()
		for i in range(max(0,y-2),min(y+3,w+2)):
			if s[max(0,x-2)][i] == "." and visited[max(0,x-2)][i]==-1:
				q.add((x-2,i))
			if s[min(h+1,x+2)][i] == "." and visited[min(h+1,x+2)][i] == -1:
				q.add((x+2,i))
		for i in range(x-1,x+2):
			if s[i][max(y-2,0)]=="." and visited[i][max(y-2,0)]==-1:
				q.add((i,y-2))
			if s[i][min(y+2,w+1)]=="." and visited[i][min(y+2,w+1)]==-1:
				q.add((i,y+2))

print(visited[dh][dw])

Submission status: Wrong Answer

Solution code:
class P:
    def __init__(self, c):
        self.c = c
        self.reached = False
        self.searched = False
        self.checked = False

from collections import deque
H, W = [int(i) for i in input().split()]
Ch, Cw = [int(i)-1 for i in input().split()]
Dh, Dw = [int(i)-1 for i in input().split()]
S = [[None for _ in range(H)] for _ in range(W)]
for y in range(H):
    tmp = input()
    for x in range(W):
        S[x][y] = P(tmp[x])

def neighbors(x, y, d):
    for i in range(max(0, x-1), min(W, x+2)):
        if S[i][y].reached == False and S[i][y].c == '.':
            d.append((i, y))
    for i in range(max(0, y-1), min(H, y+2)):
        if S[x][i].reached == False and S[x][i].c == '.':
            d.append((x, i))

def jump(x, y, d):
    S[x][y].checked = True
    for i in range(max(0, x-2), min(W, x+3)):
        for j in range(max(0, y-2), min(H, y+3)):
            if S[i][j].reached == False and S[i][j].searched == False and S[i][j].c == '.':
                d.append((i, j))
                S[i][j].searched = True


def BFS(x, y):
    if S[x][y].reached:
        return
    d = deque([(x, y)])
    while True:
        x, y = d.popleft()
        S[x][y].reached = True
        neighbors(x, y, d)
        if len(d) == 0:
            break


counter = 0
if Cw == Dw and Ch == Dh:
    print(0)
    exit()
q = deque([(Cw, Ch)])
flag = False
while True:
    while len(q) > 0:
        x, y = q.popleft()
        BFS(x, y)
    if S[Dw][Dh].reached == True:
        break
    counter += 1
    for i in range(W):
        for j in range(H):
            if S[i][j].reached and S[i][j].checked == False:
                jump(i, j, q)
    print(q)
    if len(q) == 0:
        flag = True
        break
if flag:
    print(-1)
else:
    print(counter)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
H, W = map(int, input().split())
c = [int(i) + 1 for i in input().split()]
d = [int(i) + 1 for i in input().split()]

s = []
s.append('#'*(W+4))
s.append('#'*(W+4))
for i in range(H):
    a = input()
    s.append('##' + a + '##')
s.append('#'*(W+4))
s.append('#'*(W+4))

q = deque([]) # 探索開始点
qq = deque([])
q.append((c[0], c[1], 0))
visited = [[False for __ in range(W+4)] for _ in range(H+4)]

while q:
    xx, yy, kaisuu = q.popleft()
    if visited[xx][yy] == True:
        continue
    qq.append((xx, yy, kaisuu))
    ls = deque()
    while qq:
        x, y, kaisuu = qq.pop()
        visited[x][y] = True
        ls.append((x, y, kaisuu))
        if x == d[0] and y == d[1]:
            print(kaisuu)
            sys.exit()
        if s[x+1][y] == '.' and visited[x+1][y] == False:
            qq.append((x+1, y, kaisuu))
        if s[x-1][y] == '.' and visited[x-1][y] == False:
            qq.append((x-1, y, kaisuu))
        if s[x][y+1] == '.' and visited[x][y+1] == False:
            qq.append((x, y+1, kaisuu))
        if s[x][y-1] == '.' and visited[x][y-1] == False:
            qq.append((x, y-1, kaisuu))
    for u in ls:
        a, b, e = u
        for i in range(-2, 3):
            for j in range(-2, 3):
                if i == 0 and j == 0:
                    continue
                if abs(i) == 1 and abs(j) == 1:
                    continue
                if s[a+i][b+j] == '.' and visited[a+i][b+j] == False:
                    q.append((a+i, b+j, e+1))
ans = 0
for i in range(10**100):
    ans += 1
print(-1)