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 numpy as np
from collections import deque
from numba import jit

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = np.array([input() for i in range(H)])

queue = deque()
queue.append((Ch-1, Cw-1, 0))
inf = float("inf")
table = np.array([[inf] * W for i in range(H)])
table[Ch-1][Cw-1] = 0
walk_move = ((-1, 0), (0, -1), (1, 0), (0, 1))
magic_move = []
for i in range(-2, 3):
  for j in range(-2, 3):
    if not i and not j:
      continue
    else:
      magic_move.append([i, j])

@jit
def main(maze):
  while queue:
    x, y, cost = queue.popleft()
    for i in range(-1, 1):
      for j in range(-1, 1):
        if [i,j] == [-1,1] or [i,j] == [-1,-1] or [i,j] == [1,-1] or [i,j] == [1,1]:
          continue
        dx = x+i
        dy = y+j
        if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost:
          queue.appendleft((dx, dy, cost))
          table[dx][dy] = cost
    for k in range(-2, 3):
      for l in range(-2, 3):
        if not k and not l:
          continue
        dx = x+k
        dy = y+l
        if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost+1:
          queue.append((dx, dy, cost+1))
          table[dx][dy] = cost+1
  return table[Dh-1][Dw-1]

ans = main(maze)
if ans == inf:
  print("-1")
else:
  print(int(ans))

Submission status: Wrong Answer

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

dd = [(1,0),(0,1),(-1,0),(0,-1)]
h,w = inpl()
cy,cx = inpl()
gy,gx = inpl()
cy,cx,gy,gx = cy-1,cx-1,gy-1,gx-1
s = [input() for _ in range(h)]
res = [INF] * (h*w)
seen = set()
q = deque([(cy,cx)])
res[cy*w+cx] = 0
while q:
    oy,ox = q.popleft()
    if (oy,ox) in seen: continue
    seen.add((oy,ox))
    for dy in range(-2,3):
        for dx in range(-2,3):
            ny = dy + oy
            nx = dx + ox
            if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == '.':
                f = False
                if (dy,dx) in dd:
                    if res[ny*w+nx] > res[oy*w+ox]:
                        f = True
                        res[ny*w+nx] = min(res[ny*w+nx], res[oy*w+ox])
                else:
                    if res[ny*w+nx] > res[oy*w+ox] + 1:
                        f = True
                        res[ny*w+nx] = min(res[ny*w+nx], res[oy*w+ox] + 1)
                if f: q.append((ny,nx))
print(res[gy*w+gx] if res[gy*w+gx] != INF else -1)

Submission status: Wrong Answer

Solution code:
from heapq import *
from sys import stdin
input=stdin.readline
n,m=map(int,input().split())
a,b=map(int,input().split())
x,y=map(int,input().split())
x=x-1
y=y-1
arr=[]
from math import inf
for i in range(n):
    arr.append(list(input().strip()))
def isvalid(x,y):
    if x<0 or y<0 or x>=n or y>=m or arr[x][y]=="#" :
        return False
    return True
vis=[[0]*m for i in range(n)]
stack=[[0,a-1,b-1]]
heapify(stack)
if x==a-1 and y==b-1 and arr[x][y]=="#":
    print(-1)
    quit()
mi=inf
ans=[[inf]*m for i in range(n)]
while(stack):
    cost,xx,yy=heappop(stack)
    ans[xx][yy]=cost
    if xx==x and yy==y:
        mi=min(mi,cost)
        break
    for i in [[-1,0],[1,0],[0,1],[0,-1]]:
        if isvalid(xx+i[0],yy+i[1]):
            if ans[xx+i[0]][yy+i[1]]>cost:
                heappush(stack,[cost,xx+i[0],yy+i[1]])
    for i in range(-2,3):
        for j in range(-2,3):
            if isvalid(xx+i,yy+j) and abs(i-j)!=1:
                if ans[xx+i][yy+j]>cost+1:
                    heappush(stack,[cost+1,xx+i,yy+j])
       
if mi==inf:
    print(-1)
else:
    print(mi)

Submission status: Wrong Answer

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

import heapq

INF = 10 ** 10

def dijkstra(n, G, s):
    dist = [INF] * n
    dist[s] = 0
    h = []
    heapq.heappush(h, (0, s))

    while h:
        # 使っていない頂点のうち、現時点で最も距離の近いものを選びvとする
        d, v = heapq.heappop(h)
        if dist[v] < d:
            continue
        # vから到達可能な頂点について、距離が短くなれば更新
        for end, cost in G[v]:
            if dist[end] > dist[v] + cost:
                dist[end] = dist[v] + cost
                heapq.heappush(h, (dist[end], end))
    return dist


H, W = map(int, input().split())
N = H * W
ch, cw = map(lambda x:int(x)-1, input().split())
gh, gw = map(lambda x:int(x)-1, input().split())

s = []
es = tuple([] for i in range(N))

for h in range(H):
   s.append(input().rstrip('\n'))

for h in range(H):
    for w in range(W):
        if s[h][w] != '.':
            continue
        a = h*W+w
        esappend = es[a].append
        for dh in (-2, -1, 0, 1, 2):
            for dw in (-2, -1, 0, 1, 2):
                if dh == 0 and dw == 0:
                    continue
                nh = h + dh
                nw = w + dw
                if 0 <= nh and nh < H and 0 <= nw and nw < W and s[nh][nw] == '.':
                    b = nh*W+nw
                    if (dh, dw) in [(-1,0),(1,0),(0,-1),(0,1)]:
                        esappend((b, 0))
                    else:
                        esappend((b, 1))

Submission status: Wrong Answer

Solution code:
inf = 10 ** 9
from collections import deque
def bfs(sx, sy):
    cost = [[inf] * w for i in range(h)]
    d = ((0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1))
    cost[sx - 1][sy - 1] = 0
    q = deque()
    q.append((sx - 1, sy - 1))
    
    while q:
        s, t = q.popleft()
        for dx, dy in d:
            nx = s + dx
            ny = t + dy
            
            if not(0 <= nx < h and 0 <= ny < w):continue
            if cost[nx][ny] <= cost[s][t]:continue
            if (dx + dy)%2 == 0:
                next_d = ((dx, 0), (0, dy), (dx, dy))
                for ddx, ddy in next_d:
                    nnx = nx + ddx
                    nny = ny + ddy
                    if not(0 <= nnx < h and 0 <= nny < w):continue
                    if c[nnx][nny] == '#':continue
                    if cost[nnx][nny] <= cost[s][t] + 1:continue
                    cost[nnx][nny] = cost[s][t] + 1
                    
                    if (nnx, nny) == (dh - 1, dw - 1):continue
                    q.append((nnx, nny))
                continue
                    
            elif c[nx][ny] == '.' and (dx + dy)%2 != 0:
                cost[nx][ny] = min(cost[nx][ny], cost[s][t])
                
            elif c[nx][ny] == '#' and (dx + dy)%2 != 0:
                nx += dx
                ny += dy
                if not(0 <= nx < h and 0 <= ny < w):continue
                if c[nx][ny] == '#':continue
                if cost[nx][ny] <= cost[s][t] + 1:continue
                cost[nx][ny] = cost[s][t] + 1
                
            if (nx, ny) == (dh - 1, dw - 1):continue
            q.append((nx, ny))

    return cost
        
h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())
c = [list(input()) for _ in range(h)]

res = bfs(ch, cw)
if res[dh - 1][dw - 1] == inf:print(-1)
else:print(res[dh - 1][dw - 1])

Submission status: Wrong Answer

Solution code:
from collections import deque

H ,W = map(int,input().split())
Sa,Sb = map(int,input().split())
Ga,Gb = map(int,input().split())
maze_list = [input() for i in range(H)]

Sa = Sa - 1
Sb = Sb - 1
Ga = Ga - 1
Gb = Gb - 1

que = deque()
que.append((Sa,Sb))
list_count0 = []
list_count0.append((Sa,Sb))

#全ての座標に-1の値を代入

dist = [[-1]*W for i in range(H)]
dist[Sa][Sb] = 0

#ワープ0回で行動可能な範囲の座標に0の値を代入

while len(que) > 0:
    i, j = que.popleft()
    
    for i2, j2 in ((i+1,j),(i-1,j),(i,j+1),(i,j-1)):
        if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
            continue
        if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
            dist[i2][j2] = 0
            que.append((i2,j2))
            list_count0.append((i2,j2))
        else:
            pass

#0記入のある座標からワープ1回でたどり着ける座標に１を記入（すでに０が記入されているものには記入しない）

que_count0 =deque(list_count0)
list_count1 = []

while len(que_count0) > 0:
    i, j = que_count0.popleft()
    
    for di in range(-2,3):
        for dj in range(-2,3):
            i2 = i+di
            j2 = j+dj
            
            if (i2 == i and j2 ==j):
                continue
            if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
                continue
            if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
                dist[i2][j2] = 1
                list_count1.append((i2,j2))
            else:
                pass
            
#1記入のある座標からワープ0回でたどり着ける座標に１を記入（ワープ1回でたどり着ける座標に１を記入する）

que_count1 = deque(list_count1)
list_count1_all = list_count1

while len(que_count1) > 0:
    i, j = que_count1.popleft()
    
    for i2, j2 in ((i+1,j),(i-1,j),(i,j+1),(i,j-1)):
        if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
            continue
        if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
            dist[i2][j2] = 1
            que_count1.append((i2,j2))
            list_count1_all.append((i2,j2))
        else:
            pass

#1記入のある座標からワープしてたどり着ける座標2を記入

que_count1_all = deque(list_count1_all)
list_count2 = []

while len(que_count1_all) > 0:
    i, j = que_count1_all.popleft()
    
    for di in range(-2,3):
        for dj in range(-2,3):
            i2 = i+di
            j2 = j+dj
            
            if (i2 == i and j2 ==j):
                continue
            if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
                continue
            if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
                dist[i2][j2] = 2
                list_count2.append((i2,j2))
            else:
                pass

#2記入のある座標からワープなしでたどり着ける座標に2を記入

que_count2 = deque(list_count2)

while len(que_count2) > 0:
    i, j = que_count2.popleft()
    
    for i2, j2 in ((i+1,j),(i-1,j),(i,j+1),(i,j-1)):
        if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
            continue
        if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
            dist[i2][j2] = 2
            que_count2.append((i2,j2))
        else:
            pass
        
print(dist[Ga][Gb])

Submission status: Wrong Answer

Solution code:
inf = 10 ** 9
from collections import deque
def bfs(sx, sy):
    cost = [[inf] * w for i in range(h)]
    d = ((0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1))
    cost[sx - 1][sy - 1] = 0
    q = deque()
    q.append((sx - 1, sy - 1))
    
    while q:
        s, t = q.popleft()
        for dx, dy in d:
            nx = s + dx
            ny = t + dy
            
            if not(0 <= nx < h and 0 <= ny < w):continue
            if cost[nx][ny] <= cost[s][t]:continue
            if (dx + dy)%2 == 0:
                next_d = ((dx, 0), (0, dy), (dx, dy))
                for ddx, ddy in next_d:
                    nnx = nx + ddx
                    nny = ny + ddy
                    if not(0 <= nnx < h and 0 <= nny < w):continue
                    if c[nnx][nny] == '#':continue
                    if cost[nnx][nny] <= cost[s][t] + 1:continue
                    cost[nnx][nny] = cost[s][t] + 1
                    
                    if (nnx, nny) == (dh - 1, dw - 1):continue
                    q.append((nnx, nny))
                    
            elif c[nx][ny] == '.' and (dx + dy)%2 != 0:
                cost[nx][ny] = min(cost[nx][ny], cost[s][t])
                
            elif c[nx][ny] == '#' and (dx + dy)%2 != 0:
                nx += dx
                ny += dy
                if not(0 <= nx < h and 0 <= ny < w):continue
                if c[nx][ny] == '#':continue
                if cost[nx][ny] <= cost[s][t] + 1:continue
                cost[nx][ny] = cost[s][t] + 1
                
            if (nx, ny) == (dh - 1, dw - 1):continue
            q.append((nx, ny))

    return cost
        
h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())
c = [list(input()) for _ in range(h)]

res = bfs(ch, cw)
if res[dh - 1][dw - 1] == inf:print(-1)
else:print(res[dh - 1][dw - 1])

Submission status: Wrong Answer

Solution code:
inf = 10 ** 9
from collections import deque
def bfs(sx, sy):
    cost = [[inf] * w for i in range(h)]
    d = ((0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1))
    cost[sx - 1][sy - 1] = 0
    q = deque()
    q.append((sx - 1, sy - 1))
    
    while q:
        s, t = q.popleft()
        for dx, dy in d:
            nx = s + dx
            ny = t + dy
            
            if not(0 <= nx < h and 0 <= ny < w):continue
            if cost[nx][ny] <= cost[s][t]:continue
            if c[nx][ny] == '.' and (dx + dy)%2 != 0:
                cost[nx][ny] = min(cost[nx][ny], cost[s][t])
                if (nx, ny) == (dh - 1, dw - 1):continue
                q.append((nx, ny))
                
            elif c[nx][ny] == '#' and (dx + dy)%2 != 0:
                nx += dx
                ny += dy
                if not(0 <= nx < h and 0 <= ny < w):continue
                if c[nx][ny] == '#':continue
                if cost[nx][ny] <= cost[s][t] + 1:continue
                cost[nx][ny] = cost[s][t] + 1
                if (nx, ny) == (dh - 1, dw - 1):continue
                q.append((nx, ny))

                
            elif (dx + dy)%2 == 0:
                next_d = ((dx, 0), (0, dy), (dx, dy))
                for ddx, ddy in next_d:
                    nnx = nx + ddx
                    nny = ny + ddy
                    if not(0 <= nnx < h and 0 <= nny < w):continue
                    if c[nnx][nny] == '#':continue
                    if cost[nnx][nny] <= cost[s][t] + 1:continue
                    cost[nnx][nny] = cost[s][t] + 1
                    
                    if (nnx, nny) == (dh - 1, dw - 1):continue
                    q.append((nnx, nny))
        
    return cost
        
h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())
c = [list(input()) for _ in range(h)]

res = bfs(ch, cw)
if res[dh - 1][dw - 1] == inf:print(-1)
else:print(res[dh - 1][dw - 1])

Submission status: Wrong Answer

Solution code:
from collections import deque

H ,W = map(int,input().split())
Sa,Sb = map(int,input().split())
Ga,Gb = map(int,input().split())
maze_list = [input() for i in range(H)]

Sa = Sa - 1
Sb = Sb - 1
Ga = Ga - 1
Gb = Gb - 1

que = deque()
que.append((Sa,Sb))
list_count0 = []
list_count0.append((Sa,Sb))

#全ての座標に-1の値を代入

dist = [[-1]*W for i in range(H)]
dist[Sa][Sb] = 0

#ワープ0回で行動可能な範囲の座標に0の値を代入

while len(que) > 0:
    i, j = que.popleft()
    
    for i2, j2 in ((i+1,j),(i-1,j),(i,j+1),(i,j-1)):
        if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
            continue
        if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
            dist[i2][j2] = 0
            que.append((i2,j2))
            list_count0.append((i2,j2))
        else:
            pass

#0記入のある座標からワープ1回でたどり着ける座標に１を記入（すでに０が記入されているものには記入しない）

que_count0 =deque(list_count0)
list_count1 = []

while len(que_count0) > 0:
    i, j = que_count0.popleft()
    
    for di in range(-2,3):
        for dj in range(-2,3):
            i2 = i+di
            j2 = j+dj
            
            if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
                continue
            if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
                dist[i2][j2] = 1
                list_count1.append((i2,j2))
            else:
                pass
            
#1記入のある座標からワープ0回でたどり着ける座標に１を記入（ワープ1回でたどり着ける座標に１を記入する）

que_count1 = deque(list_count1)
list_count1_all = list_count1

while len(que_count1) > 0:
    i, j = que_count1.popleft()
    
    for i2, j2 in ((i+1,j),(i-1,j),(i,j+1),(i,j-1)):
        if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
            continue
        if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
            dist[i2][j2] = 1
            que_count1.append((i2,j2))
            list_count1_all.append((i2,j2))
        else:
            pass

#1記入のある座標からワープしてたどり着ける座標2を記入

que_count1_all = deque(list_count1_all)
list_count2 = []

while len(que_count1_all) > 0:
    i, j = que_count1_all.popleft()
    
    for di in range(-2,3):
        for dj in range(-2,3):
            i2 = i+di
            j2 = j+dj
            
            if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
                continue
            if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
                dist[i2][j2] = 2
                list_count2.append((i2,j2))
            else:
                pass

#2記入のある座標からワープなしでたどり着ける座標に2を記入

que_count2 = deque(list_count2)

while len(que_count2) > 0:
    i, j = que_count2.popleft()
    
    for i2, j2 in ((i+1,j),(i-1,j),(i,j+1),(i,j-1)):
        if not (0 <= i2 <= H-1 and 0 <= j2 <= W-1):
            continue
        if maze_list[i2][j2] == "." and dist[i2][j2] == -1:
            dist[i2][j2] = 2
            que_count2.append((i2,j2))
        else:
            pass
        
print(dist[Ga][Gb])

Submission status: Wrong Answer

Solution code:
inf = 10 ** 9
from collections import deque
def bfs(sx, sy):
    cost = [[inf] * w for i in range(h)]
    d = ((0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1))
    cost[sx - 1][sy - 1] = 0
    q = deque()
    q.append((sx - 1, sy - 1))
    
    while q:
        s, t = q.popleft()
        for dx, dy in d:
            nx = s + dx
            ny = t + dy
            
            if not(0 <= nx < h and 0 <= ny < w):continue
            if cost[nx][ny] <= cost[s][t]:continue
            if c[nx][ny] == '.' and (dx + dy)%2 != 0:
                cost[nx][ny] = min(cost[nx][ny], cost[s][t])
            elif c[nx][ny] == '#' or (dx + dy)%2 == 0:
                nx += dx
                ny += dy
                if not(0 <= nx < h and 0 <= ny < w):continue
                if c[nx][ny] == '#':continue
                if cost[nx][ny] <= cost[s][t] + 1:continue
                cost[nx][ny] = cost[s][t] + 1

            if (nx, ny) == (dh - 1, dw - 1):continue
            q.append((nx, ny))
        
    return cost
        
h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())
c = [list(input()) for _ in range(h)]

res = bfs(ch, cw)
if res[dh - 1][dw - 1] == inf:print(-1)
else:print(res[dh - 1][dw - 1])

Submission status: Wrong Answer

Solution code:
import sys
mod=10**9+7 ; inf=float("inf")
from math import sqrt, ceil
from collections import deque, Counter, defaultdict #すべてのkeyが用意されてる defaultdict(int)で初期化
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)
from decimal import ROUND_HALF_UP,Decimal  #変換後の末尾桁を0や0.01で指定
  #Decimal((str(0.5)).quantize(Decimal('0'), rounding=ROUND_HALF_UP))
from functools import lru_cache
from bisect import bisect_left as bileft, bisect_right as biright
#メモ化再帰defの冒頭に毎回 @lru_cache(maxsize=10**10)
#引数にlistはだめ
#######ここまでテンプレ#######
#ソート、"a"+"b"、再帰ならPython3の方がいい
#######ここから天ぷら########

h,w=map(int,input().split())
sx,sy=map(int,input().split()) ; sx-=1;sy-=1
gx,gy=map(int,input().split()) ;gx-=1;gy-=1

A=[]
for i in range(h):
    A.append(list(input()))

dp=[[-1]*w for i in range(h)]
dp[sx][sy]=0
dx=[-1,0,1,0]
dy=[0,1,0,-1]

def warp(x,y):
    r=[]    
    for i in range(x-2,x+3):
        for j in range(y-2,y+3):
            if 0<=i<h and 0<=j<w:
                if not (i==x and j==y):
                    if A[i][j]==".":
                        r.append([i,j])
    return r


queue=deque([[sx,sy,0]])
while queue:
    flag=1
    x,y,wap=queue.pop()
    for i,j in zip(dx,dy):
        if 0<=x+i<h and 0<=y+j<w :
            if dp[x+i][y+j]==-1 and A[x+i][y+j]==".":
                flag=0
                dp[x+i][y+j]=wap
                queue.appendleft([x+i,y+j,wap])
    if flag:
        for l in warp(x,y):
            a,b=l
            if dp[a][b]==-1:
                dp[a][b]=wap+1
                queue.appendleft([a,b,wap+1])
                # print(queue)
        
                
print(dp[gx][gy])
# for i in range(h):
#   print(dp[i])

Submission status: Wrong Answer

Solution code:
from collections import deque
def main():
    h,w = map(int,input().split())
    sy,sx = map(int,input().split())
    gy,gx = map(int,input().split())
    S = []
    for _ in range(h):
        S.append(input())
    
    G = [[-1]*w for _ in range(h)]
    G_b = [[False]*w for _ in range(h)]
    v = [(1,0),(0,1),(-1,0),(0,-1)]
    ct = 0

    dq1 = deque([])
    dq1.append((sx-1,sy-1))
    G[sy-1][sx-1] = 0
    G_b[sy-1][sx-1] = True


    while dq1:

        g = set([])
        while dq1:
            x,y = dq1.popleft()
            g.add((x,y))
            for vx,vy in v:
                nx = x+vx
                ny = y+vy
                if nx>=0 and nx<w and ny>=0 and ny<h and (not G_b[ny][nx]) and S[ny][nx]==".":
                    G_b[ny][nx] = True
                    G[ny][nx] = ct
                    dq1.append((nx,ny))

        
        while g:
            x,y = g.pop()
            for i in range(-2,3):
                for j in range(-2,3):
                    if i!=0 or j!=0:
                        nx = x+i
                        ny = y+j
                        if nx>=0 and nx<w and ny>=0 and ny<h and (not G_b[ny][nx]) and S[ny][nx]==".":
                            dq1.append((nx,ny))
                            G_b[ny][nx] = True
                            G[ny][nx] = ct+1


        ct+=1
    
    print(G[gy-1][gx-1])

Submission status: Wrong Answer

Solution code:
inf = 10 ** 9
from collections import deque
def bfs(sx, sy):
    cost = [[inf] * w for i in range(h)]
    d = ((0, 1), (1, 0), (0, -1), (-1, 0))
    dd = ((0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, 1), (1, -1), (-1, -1))
    cost[sx - 1][sy - 1] = 0
    q = deque()
    q.append((sx - 1, sy - 1))
    
    while q:
        s, t = q.popleft()
        for dx, dy in d:
            nx = s + dx
            ny = t + dy
            if not(0 <= nx < h and 0 <= ny < w):continue
            if cost[nx][ny] <= cost[s][t]:continue
            if c[nx][ny] == '.':
                cost[nx][ny] = min(cost[nx][ny], cost[s][t])
            else:
                
                for ddx, ddy in dd:
                    nx += ddx
                    ny += ddy
                    if not(0 <= nx < h and 0 <= ny < w):continue
                    if c[nx][ny] == '#':continue
                    if cost[nx][ny] <= cost[s][t] + 1:continue
                    cost[nx][ny] = cost[s][t] + 1
                    
                    if (nx, ny) == (dh - 1, dw - 1):continue
                    q.append((nx, ny))
                
            if (nx, ny) == (dh - 1, dw - 1):continue
            q.append((nx, ny))
        
    return cost
        
h, w = map(int,input().split())
ch, cw = map(int,input().split())
dh, dw = map(int,input().split())
c = [list(input()) for _ in range(h)]

res = bfs(ch, cw)
if res[dh - 1][dw - 1] == inf:print(-1)
else:print(res[dh - 1][dw - 1])

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [[] for i in range(H)]
for i in range(H):
  st = input()
  for j in range(W):
    maze[i].append(st[j])
queue = deque([[Ch-1, Cw-1, 0]])
inf = float("inf")
table = [[inf for i in range(W)] for i in range(H)]
table[Ch-1][Cw-1] = 0
walk_move = [[-1, 0], [0, -1], [1, 0], [0, 1]]
magic_move = []
for i in range(-2, 3):
  for j in range(-2, 3):
    if not i and not j:
      continue
    else:
      magic_move.append([i, j])

while queue:
  x, y, cost = queue.popleft()
  for i,j in walk_move:
    dx = x+i
    dy = y+j
    if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost:
      queue.appendleft([dx, dy, cost])
      table[dx][dy] = min(table[dx][dy], table[x][y])
  for k,l in magic_move:
    dx = x+k
    dy = y+l
    if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and table[dx][dy] > cost+1:
      queue.append([dx, dy, cost+1])
      table[dx][dy] = min(table[dx][dy], table[x][y]+1)
      
print(table[Dh-1][Dw-1])

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = map(int,input().split())
CH, CW = map(int,input().split())
DH, DW = map(int,input().split())

S = []
for _ in range(H):
    S.append(list(input()))

d = [[-1 for i in range(W)] for j in range(H)]

Q = deque([[CH-1, CW-1, 0]])
d[CH - 1][CW - 1] = 0

while len(Q) != 0:
    x, y, cnt = Q.popleft()
    
    d[x][y] = cnt
    
    for tx in range(-2, 3):
        for ty in range(-2, 3):
            nx = x + tx
            ny = y + ty
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "." and d[nx][ny] == -1:
                if abs(tx) + abs(ty) == 1:
                    Q.appendleft([nx, ny, cnt])
                elif abs(tx) + abs(ty) >= 2:
                    Q.append([nx, ny, cnt + 1])

print(d[DH - 1][DW - 1])

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [[] for i in range(H)]
for i in range(H):
  st = input()
  for j in range(W):
    maze[i].append(st[j])
queue = deque([[Ch-1, Cw-1]])
inf = float("inf")
table = [[inf for i in range(W)] for i in range(H)]
table[Ch-1][Cw-1] = 0
walk_move = [[-1, 0], [0, -1], [1, 0], [0, 1]]
magic_move = []
for i in range(-2, 3):
  for j in range(-2, 3):
    if not i and not j:
      continue
    else:
      magic_move.append([i, j])

walk_queue = deque([[Ch-1, Cw-1]])
magic_queue = deque([Ch-1, Cw-1])
while queue:
  x, y = queue.popleft()
  for i,j in walk_move:
    dx = x+i
    dy = y+j
    if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and not [dx,dy] in walk_queue:
      queue.appendleft([dx, dy])
      walk_queue.append([dx, dy])
      table[dx][dy] = min(table[dx][dy], table[x][y])
  for k,l in magic_move:
    dx = x+k
    dy = y+l
    if 0 <= dx <= H-1 and 0 <= dy <= W-1 and maze[dx][dy] == "." and not [dx, dy] in magic_queue:
      queue.append([dx, dy])
      magic_queue.append([dx, dy])
      table[dx][dy] = min(table[dx][dy], table[x][y]+1)
      
print(table[Dh-1][Dw-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys

H, W = map(int,input().split())
CH, CW = map(int,input().split())
DH, DW = map(int,input().split())

S = []
for _ in range(H):
    S.append(list(input()))

d = [[-1 for i in range(W)] for j in range(H)]

Q = deque([[CH-1, CW-1, 0]])
d[CH - 1][CW - 1] = 0

while len(Q) != 0:
    x, y, cnt = Q.popleft()
    
    d[x][y] = cnt
    
    for tx in range(-2, 3):
        for ty in range(-2, 3):
            nx = x + tx
            ny = y + ty
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "." and d[nx][ny] == -1:
                if abs(tx)+abs(ty) == 1:
                    Q.appendleft([nx, ny, cnt])
                elif abs(tx)+abs(ty) >= 2:
                    Q.append([nx, ny, cnt + 1])

print(d[DH - 1][CH - 1])

Submission status: Wrong Answer

Solution code:
# D - Wizard in Maze
import sys
from collections import deque
from typing import List, Tuple


class WarpableMaze:
    __slots__ = ["height", "width", "is_unsearched", "dist"]

    def __init__(
        self, height: int, width: int, grid: List[bytes], road: str = ".",
    ) -> None:
        self.height = height + 4
        self.width = width + 4
        self.is_unsearched = 1 << 30
        self.dist = self._convert_grid_to_dist(grid, road)

    def _convert_grid_to_dist(self, grid: List[bytes], road: str) -> List[int]:
        dist = [-1] * self.height * self.width
        i = self.width * 2 + 1
        for row in grid:
            for c in row.decode():
                i += 1
                if c == road:
                    dist[i] = self.is_unsearched
            i += 4
        return dist

    def _flatten_coordinate(self, x: int, y: int) -> int:
        """Values of a coordinate must be 1-origin."""
        return self.width * (x + 1) + y + 1

    def bfs(self, start_2d: Tuple[int, int], goal_2d: Tuple[int, int]) -> int:
        start = self._flatten_coordinate(*start_2d)
        goal = self._flatten_coordinate(*goal_2d)

        w = self.width
        walk_to_warp = {
            -w: (-2 * w - 2, -2 * w - 1, -2 * w, -2 * w + 1, -w - 1),
            w: (w + 1, 2 * w - 1, 2 * w, 2 * w + 1, 2 * w + 2),
            -1: (-w - 2, -2, w - 2, w - 1, 2 * w - 2),
            1: (-w + 1, -2 * w + 2, -w + 2, 2, w + 2),
        }

        dist = self.dist[:]
        dist[start] = 0
        queue = deque([start])
        while queue:
            x = queue.popleft()
            cur_dist = dist[x]
            if x == goal:
                break

            for walk, warp in walk_to_warp.items():
                nx = x + walk
                if dist[nx] == self.is_unsearched:
                    dist[nx] = cur_dist
                    queue.appendleft(nx)
                    continue
                if dist[nx] >= 0:
                    continue

                for dx in warp:
                    nx = x + dx
                    if dist[nx] > cur_dist + 1:
                        dist[nx] = cur_dist + 1
                        queue.append(nx)

        return dist[goal] if dist[goal] != self.is_unsearched else -1


def main():
    read = sys.stdin.buffer.read
    readline = sys.stdin.buffer.readline

    H, W = map(int, readline().split())
    (*start,) = map(int, readline().split())
    (*goal,) = map(int, readline().split())
    (*S,) = read().split()

    maze = WarpableMaze(H, W, S)
    print(maze.bfs(start, goal))


if __name__ == "__main__":
    main()