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
import re
import queue
from math import ceil, floor, sqrt, pi, factorial, gcd
from copy import deepcopy
from collections import Counter, deque
from heapq import heapify, heappop, heappush
from itertools import accumulate, product, combinations, combinations_with_replacement
from bisect import bisect, bisect_left, bisect_right
from functools import reduce
from decimal import Decimal, getcontext
# input = sys.stdin.readline
def i_input(): return int(input())
def i_map(): return map(int, input().split())
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 6)
INF = float('inf')
MOD = 10 ** 9 + 7
num_list = []
str_list = []

def isIn(H,W,x,y):
	if 0<= x and x <= H-1 and 0<=y and y<=W-1:
		return True
	else:
		return False

def main():
	H,W = i_map()

	C_h,C_w = i_map()
	D_h,D_w = i_map()

	S = []
	for i in range(0,H):
		tmp = s_input()
		tmp2 = []
		for j in range(0,W):
			tmp2.append(tmp[j])
		S.append(tmp2)

	start = [C_h-1,C_w-1]
	exit = [D_h-1,D_w-1]

	rel_matrix = [([[] for i in range(W)]) for i in range(H)]
	dir = [[-1,0],[1,0],[0,-1],[0,1]]
	for i in range(0,H):
		for j in range(0,W):
			for v_dir in dir:
				if isIn(H,W,i+v_dir[0],j+v_dir[1]):
					if(S[i][j] == '.' and S[i+v_dir[0]][j+v_dir[1]] == '.'):
						rel_matrix[i][j].append((i+v_dir[0],j+v_dir[1]))

	color = [['white' for i in range(W)] for j in range(H)]
	cost = [[-1 for i in range(W)] for j in range(H)]
	
	q =  queue.Queue()
	cost[start[0]][start[1]] = 0
	color[start[0]][start[1]]='gray'
	q.put(start)
	while(not q.empty()):
		u = q.get()
		for rel in rel_matrix[u[0]][u[1]]:
			if color[rel[0]][rel[1]] == 'white':
				cost[rel[0]][rel[1]] = 0
				color[rel[0]][rel[1]]  = 'gray'
				q.put(rel)
		color[u[0]][u[1]] = 'black'

	currentList = []
	for i in range(0,H):
		for j in range(0,W):
			if(cost[i][j] == 0):
				currentList.append((i,j))

	nextList  = []
	for kouho in currentList:
		for i in range(-2,3):
			for j in range(-2,3):
				if(kouho[0]+i >= 0 and kouho[0]+i <= H-1 and kouho[1] + j >= 0 and kouho[1] + j <= W-1):
					if(S[kouho[0]+i][kouho[1]+j]=='.' and color[kouho[0]+i][kouho[1]+j] == 'white'):
						nextList.append((kouho[0]+i,kouho[1]+j))
	for next in nextList:
		q2 = queue.Queue()
		cost[next[0]][next[1]] =1
		color[next[0]][next[1]] = 'gray'
		q2.put((next[0],next[1]))
		while(not q2.empty):
			u = q2.get()
			for rel in rel_matrix[u[0]][u[1]]:
				if color[rel[0]][rel[1]] == 'white':
					cost[rel[0]][rel[1]] = 1
					color[rel[0]][rel[1]]  = 'gray'
					q2.put(rel)
			color[u[0]][u[1]] = 'black'

	print(cost[D_h-1][D_w-1])



if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
import collections

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [input() for _ in range(H)]
INF = 10**10
cost = [[INF] * W for _ in range(H)]
cost[Ch - 1][Cw - 1] = 0
walk = [(-1, 0), (0, 1), (0, -1), (1, 0)]
warp = [(-2, 2), (-2, 1), (-2, 0), (-2, -1), (-2, -2), (-1, 2), (-1, 1), (-1, -1), (-1, -2), (0, 2), (0, -2), (1, 2), (1, 1), (1, -1), (1, -2), (2, 2), (2, 1), (2, 0), (2, -1), (2, -2)]

q = collections.deque([[Ch - 1, Cw - 1, 0]])
while q:
  h, w, c = q.popleft()
  
  for wk in walk:
    dh, dw = wk
    nh = h + dh
    nw = w + dw
  
    if 0 <= nh <= H - 1 and 0 <= nw <= W - 1 and maze[nh][nw] == "." and c < cost[nh][nw]:
      cost[nh][nw] = c
      q.appendleft([nh, nw, c])

  for wp in warp:
    dh, dw = wp
    nh = h + dh
    nw = w + dw
  
    if 0 <= nh <= H - 1 and 0 <= nw <= W - 1 and maze[nh][nw] == "." and c + 1 < cost[nh][nw]:
      cost[nh][nw] = c
      q.append([nh, nw, c + 1])

print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != INF else -1)

Submission status: Wrong Answer

Solution code:
import collections

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [input() for _ in range(H)]
INF = 10**10
cost = [[INF] * W for _ in range(H)]
cost[Ch - 1][Cw - 1] = 0
walk = [(-1, 0), (0, 1), (0, -1), (1, 0)]
warp = [(-2, 2), (-2, 1), (-2, 0), (-2, -1), (-2, -2), (-1, 2), (-1, 1), (-1, -1), (-1, -2), (0, 2), (0, -2), (1, 2), (1, 1), (1, -1), (1, -2), (2, 2), (2, 1), (2, 0), (2, -1), (2, -2)]

q = collections.deque([[Ch - 1, Cw - 1, 0]])
while q:
  h, w, c = q.popleft()
  
  for wk in walk:
    dh, dw = wk
    nh = h + dh
    nw = w + dw
  
    if 0 <= nh <= H - 1 and 0 <= nw <= W - 1 and maze[nh][nw] == "." and c + 1 < cost[nh][nw]:
      cost[nh][nw] = c
      q.appendleft([nh, nw, c])

  for wp in warp:
    dh, dw = wp
    nh = h + dh
    nw = w + dw
  
    if 0 <= nh <= H - 1 and 0 <= nw <= W - 1 and maze[nh][nw] == "." and c + 1 < cost[nh][nw]:
      cost[nh][nw] = c
      q.append([nh, nw, c + 1])

print(cost[Dh - 1][Dw - 1] if cost[Dh - 1][Dw - 1] != INF else -1)

Submission status: Wrong Answer

Solution code:
from collections import deque

def main():
  h,w=map(int,input().split())
  cy,cx=map(int,input().split())
  dy,dx=map(int,input().split())

  M=["##"+input()+"##" for x in range(h)]
  for i in range(2):
    M.insert(0,"#"*(w+4))
    M.append("#"*(w+4))

  C=[[-1 if M[j][i]=="." else -2 for i in range(w+4)] for j in range(h+4)]
  C[-~cy][-~cx]=0
  QA,QB=deque(),deque()
  QA.append((-~cy,-~cx,0))
  W=[[i,j] for i in range(-2,3) for j in range(-2,3) if abs(i)+abs(j)>1]

  while QA:
    h,w,c=QA.popleft()
    QB.append((h,w,c))

    for i,j in [[1,0],[0,1],[-1,0],[0,-1]]:
      dh,dw=h+i,w+j
      if C[dh][dw]==-1:
        C[dh][dw]=c
        QA.appendleft((dh,dw,c))

    if QA:
      continue

    while QB:
      h,w,c=QB.popleft()
      for i,j in W:
        dh,dw=h+i,w+j
        if C[dh][dw]==-1:
          C[dh][dw]=-~c
          QA.append((dh,dw,-~c))

    if C[-~dy][-~dx]!=-1:
      print(C[-~dy][-~dx])
      exit()

if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
# https://yamakasa.net/atcoder-abc-176-d/
# 迷路の入力をsys.stdinを使ってやる

from collections import deque
from sys import stdin
import sys

# 入力
H, W = map(int, input().split())
C_h, C_w = map(int, input().split())
D_h, D_w = map(int, input().split())
maze = []
for i in range(H):
    maze.append(list(stdin.readline()[:-1]))

# IDをまとめる表、-1で初期化
ID = [[-1] * W for i in range(H)]

# 移動Aで動ける範囲のマスは同一のIDを持つとして、IDを割り振る
id = 0
for x in range(H):
    for y in range(W):
        if maze[x][y]  == "." and ID[x][y] == -1:  # 到達可能でまだIDが割り振られていない点
            #ID[x][y] = id
            # BFSで同一のIDを持つ領域をくまなく探索
            que = deque([])
            que.append((x, y))
            while que:
                temp_x, temp_y = que.popleft()
                ID[temp_x][temp_y] = id
                for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
                    nx = temp_x + dx
                    ny = temp_y + dy
                    if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == "." and ID[nx][ny] == -1:
                        que.append((nx, ny))

            id += 1

# ワープ可能なID同士の繋がりを記録
ID_graph = [[0] * id for i in range(id)]  # IDmとIDnの間がワープ可能ならID[m][n] = 1、そうでなければID[m][n] = 0
for x in range(H):
    for y in range(W):
        if maze[x][y] != "#" and ID[x][y] != -1:  # IDが割り振られている点
            for dx in range(-2, 3):
                for dy in range(-2, 3):
                    if abs(dx) + abs(dy) >= 2:  # 移動Aでは移動不可で移動Bでは移動可能なマス
                        nx = x + dx
                        ny = x + dy
                        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] != "#" and ID[x][y] != ID[nx][ny]:
                            ID_graph[ID[x][y]][ID[nx][ny]] = 1
                            ID_graph[ID[nx][ny]][ID[x][y]] = 1

# ID間の関係から最短距離を求める
ID_score = [float("inf")] * id  # 各IDまで何回のワープでたどり着けるか、INFで初期化
init_ID = ID[C_h-1][C_w-1]  # 初期位置
ID_score[init_ID] = 0

que = deque([])
que.append(init_ID)
while que:
    temp_id = que.popleft()
    if temp_id == ID[D_h-1][D_w-1]:  # ゴールのIDに到達
        break
    for k in range(id):
        if ID_graph[temp_id][k] == 1 and ID_score[k] == float("inf"):  # 今着目しているIDからワープできてまだ見ていないID
            que.append(k)
            ID_score[k] = ID_score[temp_id] + 1

if ID_score[ID[D_h-1][D_w-1]] != float("inf"):
    print(ID_score[ID[D_h-1][D_w-1]])
else:
    print(-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 = list(input() for _ in range(H))
d = [[10**9]*W for _ in range(H)]
d[Ch-1][Cw-1] = 0

D = deque([(Ch-1, Cw-1)])
while D:
    h, w = deque.popleft(D)
    c = d[h][w]
    # 歩いて移動
    # 上
    if h > 0:
        if S[h-1][w] == "." and c < d[h-1][w]:
            d[h-1][w] = c
            deque.append(D, (h-1, w))
    # 下
    if h < H-1:
        if S[h+1][w] == "." and c < d[h+1][w]:
            d[h+1][w] = c
            deque.append(D, (h+1, w))
    # 左
    if w > 0:
        if S[h][w-1] == "." and c < d[h][w-1]:
            d[h][w-1] = c
            deque.append(D, (h, w-1))
    # 右
    if w < W-1:
        if S[h][w+1] == "." and c < d[h][w+1]:
            d[h][w+1] = c
            deque.append(D, (h, w+1))
    # ワープで移動
    for hh in range(max(0, h-2), min(H-1, h+2)+1):
        for ww in range(max(0, w-2), min(W-1, w+2)+1):
            if S[hh][ww] == "." and d[hh][ww] > c+1:
                d[hh][ww] = c+1
                deque.append(D, (hh, ww))
if d[Dh-1][Dw-1] == 10**9:
    print(-1)
else:
    print(d[Dh-1][Dw-1])
print(d)

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 = list(input() for _ in range(H))
d = [[10**9]*W for _ in range(H)]
d[Ch-1][Cw-1] = 0

D = deque([(Ch-1, Cw-1)])
while D:
    tmp = deque.popleft(D)
    h, w = tmp[0], tmp[1]
    c = d[h][w]
    # 歩いて移動
    # 上
    if h > 0:
        if S[h-1][w] == "." and c < d[h-1][w]:
            d[h-1][w] = c
            deque.append(D, (h-1, w))
    # 下
    if h < H-1:
        if S[h+1][w] == "." and c < d[h+1][w]:
            d[h+1][w] = c
            deque.append(D, (h+1, w))
    # 左
    if w > 0:
        if S[h][w-1] == "." and c < d[h][w-1]:
            d[h][w-1] = c
            deque.append(D, (h, w-1))
    # 右
    if w < W-1:
        if S[h][w+1] == "." and c < d[h][w+1]:
            d[h][w+1] = c
            deque.append(D, (h, w+1))
    # ワープで移動
    for h in range(max(0, h-2), min(H-1, h+2)):
        for w in range(max(0, w-2), min(W-1, w+2)):
            if S[h][w] == "." and d[h][w] > c+1:
                d[h][w] = c+1
                deque.append(D, (h, w))
if d[Dh-1][Dw-1] == 10**9:
    print(-1)
else:
    print(d[Dh-1][Dw-1])

Submission status: Wrong Answer

Solution code:
# https://yamakasa.net/atcoder-abc-176-d/

from collections import deque
import sys

# 入力
H, W = map(int, input().split())
C_h, C_w = map(int, input().split())
D_h, D_w = map(int, input().split())
maze = []
for i in range(H):
    maze.append(list(input()))

# IDをまとめる表、-1で初期化
ID = [[-1] * W for i in range(H)]

# 移動Aで動ける範囲のマスは同一のIDを持つとして、IDを割り振る
id = 0
for x in range(H):
    for y in range(W):
        if maze[x][y]  == "." and ID[x][y] == -1:  # 到達可能でまだIDが割り振られていない点
            #ID[x][y] = id
            # BFSで同一のIDを持つ領域をくまなく探索
            que = deque([])
            que.append((x, y))
            while que:
                temp_x, temp_y = que.popleft()
                ID[temp_x][temp_y] = id
                for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:
                    nx = temp_x + dx
                    ny = temp_y + dy
                    if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == "." and ID[nx][ny] == -1:
                        que.append((nx, ny))

            id += 1

# ワープ可能なID同士の繋がりを記録
ID_graph = [[0] * id for i in range(id)]  # IDmとIDnの間がワープ可能ならID[m][n] = 1、そうでなければID[m][n] = 0
for x in range(H):
    for y in range(W):
        if maze[x][y] != "#" and ID[x][y] != -1:  # IDが割り振られている点
            for dx in range(-2, 3):
                for dy in range(-2, 3):
                    if abs(dx) + abs(dy) >= 2:  # 移動Aでは移動不可で移動Bでは移動可能なマス
                        nx = x + dx
                        ny = x + dy
                        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] != "#" and ID[x][y] != ID[nx][ny]:
                            ID_graph[ID[x][y]][ID[nx][ny]] = 1
                            ID_graph[ID[nx][ny]][ID[x][y]] = 1

# ID間の関係から最短距離を求める
ID_score = [float("inf")] * id  # 各IDまで何回のワープでたどり着けるか、INFで初期化
init_ID = ID[C_h-1][C_w-1]  # 初期位置
ID_score[init_ID] = 0

que = deque([])
que.append(init_ID)
while que:
    temp_id = que.popleft()
    if temp_id == ID[D_h-1][D_w-1]:  # ゴールのIDに到達
        break
    for k in range(id):
        if ID_graph[temp_id][k] == 1 and ID_score[k] == float("inf"):  # 今着目しているIDからワープできてまだ見ていないID
            que.append(k)
            ID_score[k] = ID_score[temp_id] + 1

if ID_score[ID[D_h-1][D_w-1]] != float("inf"):
    print(ID_score[ID[D_h-1][D_w-1]])
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from sys import stdin

def main():
    h,w = map(int, stdin.readline().split())
    sh,sw = map(int, stdin.readline().split())
    gh,gw = map(int, stdin.readline().split())
    dist = [[-2] * (w+4) for _ in range(h+4)] 

    for i in range(h):
        ix = i+2
        iy = 1
        for v in list(stdin.readline()):
            iy += 1
            if v == ".":
                dist[ix][iy] = -1

    sh+=1
    sw+=1
    gh+=1
    gw+=1

    move = [[-1, 0], [1, 0], [0, -1], [0, 1]]
    magic = [[-2, -2], [-2, -1], [-2, 0], [-2, 1], [-2, 2], [-1, -2], [-1, -1], [-1, 1], [-1, 2], [0, -2], [0, 2], [1, -2], [1, -1], [1, 1], [1, 2], [2, -2], [2, -1], [2, 0], [2, 1], [2, 2]]

    queue = []
    queue.append([sh,sw])
    dist[sh][sw] = 0
    check_list = []
    while len(queue) > 0:
        x, y = queue.pop(0)
        check_list.append([x,y])
        for p, q in move:
            nx = x + p
            ny = y + q
            if dist[nx][ny] == -1:
                queue.append([nx,ny])
                dist[nx][ny] = dist[x][y]
                check_list.append([nx,ny])
                if [nx, ny] == [gh, gw]:
                    return True
        
        if len(queue) == 0:
            while len(check_list) > 0:
                x2, y2 = check_list.pop(0) 
                for p2, q2 in magic:
                    nx2 = x2 + p2
                    ny2 = y2 + q2
                    if dist[nx2][ny2] == -1:
                        dist[nx2][ny2] = dist[x2][y2]+1
                        queue.append([nx2, ny2])
    print(dist[gh][gw])

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

h, w = map(int, input().split())
sy,sx = map(int,input().split())
gy,gx = map(int,input().split())
sy,sx = sy-1,sx-1
gy,gx = gy-1,gx-1
s = []
for i in range(h):
    s.append(list(input()))

# 無限大
INF = float('inf')
ans = -1
# 距離
dist = [[INF for j in range(w)] for i in range(h)]
dist[sy][sx] = 0

q = deque([(sx, sy)])

while len(q) != 0:
    x, y = q.popleft()
    for dx in range(-2, 3):
        for dy in range(-2, 3):
            if dx == dy == 0: continue
            if not(0 <= x+dx < w): continue
            if not(0 <= y+dy < h): continue
            if s[y+dy][x+dx] == "#": continue
            if dist[y+dy][x+dx] != INF: continue

            if abs(dx) + abs(dy) <= 1:
                # 徒歩移動
                if dist[y+dy][x+dx] <= dist[y][x]: continue
                
                dist[y+dy][x+dx] = dist[y][x]
                q.appendleft((x+dx, y+dy))
            else:
                # 魔法移動
                if dist[y+dy][x+dx] <= dist[y][x] + 1: continue
                
                dist[y+dy][x+dx] = dist[y][x] + 1
                q.append((x+dx, y+dy))

if dist[gy][gx] == INF:
    print(-1)
else:
    print(dist[gy][gx])

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())
# ch -= 1
# cw -= 1
# dh -= 1
# dw -= 1
sy,sx = map(int,input().split())
gy,gx = map(int,input().split())
sy,sx = sy-1,sx-1
gy,gx = gy-1,gx-1
s = []
for i in range(h):
    s.append(list(input()))

# 無限大
INF = float('inf')
ans = -1
# 距離
dist = [[INF for j in range(w)] for i in range(h)]
# dist[ch][cw] = 0
dist[sy][sx] = 0

q = deque([(sx, sy)])

while len(q) != 0:
    x, y = q.popleft()
    for dx in range(-2, 3):
        for dy in range(-2, 3):
            if dx == dy == 0: continue
            if not(0 <= x+dx < w): continue
            if not(0 <= y+dy < h): continue
            if s[y+dy][x+dx] == "#": continue
            if dist[y+dy][x+dx] != INF: continue

            if abs(dx) + abs(dy) <= 1:
                # 徒歩移動
                if dist[y+dy][x+dx] <= dist[y][x]: continue
                
                dist[y+dy][x+dx] = dist[y][x]
                q.appendleft((x+dx, y+dy))
            else:
                # 魔法移動
                if dist[y+dy][x+dx] <= dist[y][x] + 1: continue
                
                dist[y+dy][x+dx] = dist[y][x] + 1
                q.append((x+dx, y+dy))
# print(s)
# print(dist)

if dist[gy][gx] == INF:
    print(-1)
else:
    print(dist[gy][gx])

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
start = list(map(int, input().split()))
goal = list(map(int, input().split()))
field = [list(input()) for _ in range(H)]

walk = ((0, 1), (1, 0), (-1, 0), (0, -1))
warp = ((0, 2), (2, 0), (-2, 0), (0, -2), (2, 2), (-2, 2),
        (2, -2), (-2, -2), (1, 1), (-1, 1), (1, -1), (-1, -1), (1, 2), (2, 1), (-1, -2), (-1, 2), (1, -2), (-2, -1), (-2, 1), (2, -1))


def dfs(start, color, move):
    current = [start]
    color = str(color)
    colored_pos = [start]
    while current:
        next = []
        for now in current:
            for m in move:
                t = [now[0] + m[0], now[1] + m[1]]
                if not(t[0] < 1 or t[1] < 1 or t[0] > H or t[1] > W):
                    if field[t[0]-1][t[1]-1] == ".":
                        next.append(t)
                        colored_pos.append(t)
            for n in next:
                field[n[0]-1][n[1]-1] = color
                if n[0] == goal[0] and n[1] == goal[1]:
                    print(int(color))
                    exit()
        current = next
    return colored_pos


def colorWarp(p, color, next_move_group):
    for w in warp:
        t = (p[0]+w[0], p[1]+w[1])
        if not(t[0] < 1 or t[1] < 1 or t[0] > H or t[1] > W):
            if field[t[0]-1][t[1]-1] == ".":
                if t[0] == goal[0] and t[1] == goal[1]:
                    print(color)
                    exit()
                field[t[0]-1][t[1]-1] = str(color)
                next_move_group.append(t)


def printMap():
    for _ in range(H):
        print(" ".join(field[_]))


color = 0
field[start[0]-1][start[1]-1] = str(color)
current_move_group = [start]
while current_move_group:
    colored_pos = []
    for now in current_move_group:
        result = dfs(now, color, walk)
    for x in result:
        colored_pos.append(x)
    color += 1
    # warpで移動かのな場所を確認する。
    next_move_group = []
    for p in colored_pos:
        colorWarp(p, color, next_move_group)
    current_move_group = next_move_group
print(-1)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
start = list(map(int, input().split()))
goal = list(map(int, input().split()))
field = [list(input()) for _ in range(H)]

walk = ((0, 1), (1, 0), (-1, 0), (0, -1))
warp = ((0, 2), (2, 0), (-2, 0), (0, -2), (2, 2), (-2, 2),
        (2, -2), (-2, -2), (1, 1), (-1, 1), (1, -1), (-1, -1), (1, 2), (2, 1), (-1, -2), (-1, 2), (1, -2), (-2, -1), (-2, 1), (2, -1))


def dfs(start, color, move):
    current = [start]
    color = str(color)
    colored_pos = [start]
    while current:
        next = []
        for now in current:
            for m in move:
                t = [now[0] + m[0], now[1] + m[1]]
                if not(t[0] < 1 or t[1] < 1 or t[0] > H or t[1] > W):
                    if field[t[0]-1][t[1]-1] == ".":
                        next.append(t)
                        colored_pos.append(t)
            for n in next:
                field[n[0]-1][n[1]-1] = color
                if n[0] == goal[0] and n[1] == goal[1]:
                    print(int(color))
                    exit()
        current = next
    return colored_pos


def colorWarp(p, color, next_move_group):
    for w in warp:
        t = (p[0]+w[0], p[1]+w[1])
        if not(t[0] < 1 or t[1] < 1 or t[0] > H or t[1] > W):
            if field[t[0]-1][t[1]-1] == ".":
                if t[0] == goal[0] and t[1] == goal[1]:
                    print(color)
                    exit()
                field[t[0]-1][t[1]-1] = str(color)
                next_move_group.append(t)


def printMap():
    for _ in range(H):
        print(" ".join(field[_]))


color = 0
field[start[0]-1][start[1]-1] = str(color)
current_move_group = [start]
while current_move_group:
    colored_pos = []
    for now in current_move_group:
        result = dfs(now, color, walk)
    for x in result:
        colored_pos.append(x)
    if not colored_pos:
        print(-1)
        exit()
    color += 1
    # warpで移動かのな場所を確認する。
    next_move_group = []
    for p in colored_pos:
        colorWarp(p, color, next_move_group)
    current_move_group = next_move_group
print(-1)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
start = list(map(int, input().split()))
goal = list(map(int, input().split()))
field = [list(input()) for _ in range(H)]

now = start
walk = ((0, 1), (1, 0), (-1, 0), (0, -1))
warp = ((0, 2), (2, 0), (-2, 0), (0, -2), (2, 2), (-2, 2),
        (2, -2), (-2, -2), (1, 1), (-1, 1), (1, -1), (-1, -1), (1, 2), (2, 1), (-1, -2), (-1, 2), (1, -2), (-2, -1), (-2, 1), (2, -1))


def dfs(start, color, move):
    current = [start]
    color = str(color)
    colored_pos = [start]
    while current:
        next = []
        for now in current:
            for m in move:
                t = [now[0] + m[0], now[1] + m[1]]
                if not(t[0] < 1 or t[1] < 1 or t[0] > H or t[1] > W):
                    if field[t[0]-1][t[1]-1] == ".":
                        next.append(t)
                        colored_pos.append(t)
            for n in next:
                field[n[0]-1][n[1]-1] = color
                if n[0] == goal[0] and n[1] == goal[1]:
                    print(int(color)-1)
                    exit()
        current = next
    return colored_pos


def colorWarp(p, color, next_move_group):
    for w in warp:
        t = (p[0]+w[0], p[1]+w[1])
        if not(t[0] < 1 or t[1] < 1 or t[0] > H or t[1] > W):
            if field[t[0]-1][t[1]-1] == ".":
                if t[0] == goal[0] and t[1] == goal[1]:
                    print(color)
                    exit()
                field[t[0]-1][t[1]-1] = str(color)
                next_move_group.append(t)


def printMap():
    for _ in range(H):
        print(" ".join(field[_]))


color = 0
field[start[0]-1][start[1]-1] = str(color)
current_move_group = [start]
while current_move_group:
    colored_pos = []
    for now in current_move_group:
        result = dfs(now, 1, walk)
    for x in result:
        colored_pos.append(x)
    if not colored_pos:
        print(-1)
        exit()
    color += 1
    # warpで移動かのな場所を確認する。
    next_move_group = []
    for p in colored_pos:
        colorWarp(p, color, next_move_group)
    current_move_group = next_move_group
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())
S = [list(input()) for _ in range(H)]

INF = H * W

dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

# def steppable(h,w):
#     if not (h in range(H)) or not (w in range(W)):
#         return False
#     if S[h][w] == '#':
#         return False
#     else:
#         return True

num_step = [[INF for w in range(W)] for h in range(H)]
num_step[Ch - 1][Cw - 1] = 0

# スタート地点を定義
queue = [(Ch - 1, Cw - 1)]
num_warp = 0

# 幅優先探索
while not queue == []:
    magic_tiles = []
    while not queue == []:
        h = queue.pop(0) # here 
        if h[0] == Dh - 1 and h[1] == Dw - 1:
            print(num_warp)
            exit()
        # next_  = [
        #     (h[0] + 1, h[1], 0),
        #     (h[0] - 1, h[1], 0),
        #     (h[0], h[1] + 1, 0),
        #     (h[0], h[1] - 1, 0),]
        for i in range(4):
            if 0 <= h[0]+dy[i] < H and 0 <= h[1]+dx[i] < W and S[h[0]+dy[i]][h[1]+dx[i]] == '.' and num_step[h[0]+dy[i]][h[1]+dx[i]] > num_warp:
                queue.append((h[0]+dy[i], h[1]+dx[i]))
                num_step[h[0]+dy[i]][h[1]+dx[i]] = num_warp

        # 魔法を使っていける場所を検討
        dx = [-2, -1 , 0, 1, 2]
        dy = [-2, -1 , 0, 1, 2]

        for x in dx:
            for y in dy:
                 if 0 <= h[0] + y < H and 0 <= h[1] + x < W and S[h[0] + y][h[1] + x] == '.' \
                     and num_step[h[0] + y][h[1] + x] == INF:
                    magic_tiles.append((h[0] + y, h[1] + x))

    num_warp += 1

    # キューの追加
    for magic in magic_tiles:
        if num_step[magic[0]][magic[1]] == INF:
            num_step[magic[0]][magic[1]] == num_warp
            queue.append((magic[0],magic[1]))

print(-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())
Ch, Cw, Dh, Dw = Ch-1, Cw-1, Dh-1, Dw-1

maze = [input() for _ in range(H)]
visit = [[-1] * W for _ in range(H)]
visit[Ch][Cw] = 0

DQ = deque([[Ch, Cw]])
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

while DQ:
  px, py = DQ.popleft()
  if px==Dh and py==Dw:
    print(visit[px][py])
    exit()
  
  for i in range(4):
    nx = px + dx[i]
    ny = py + dy[i]
    if 0<=nx<=H-1 and 0<=ny<=W-1 and maze[nx][ny]=="." and  (visit[nx][ny]>visit[px][py] or visit[nx][ny]==-1):
      visit[nx][ny] = visit[px][py]
      DQ.append([nx, ny])
    
  for i in range(-2, 3):
    for j in range(-2, 3):
      if i==j==0:
        continue
      nx = px + i
      ny = py + j
      if 0<=nx<=H-1 and 0<=ny<=W-1 and maze[nx][ny]=="." and visit[nx][ny]==-1:
        visit[nx][ny] = visit[px][py] + 1
        DQ.append([nx, ny])

print(-1)

Submission status: Wrong Answer

Solution code:
import copy
from collections import deque
H,W = map(int, input().split())
Ch,Cw = map(int, input().split())
Dh,Dw = map(int, input().split())
maze = []
vis=[]
stack = deque([[Ch-1,Cw-1]])

def privis():
  for v in vis:
    print(v)
  print("/n")

for h in range(H):
  maze.append(list(input()))
  vis.append([1e9]*W)

vis[Ch-1][Cw-1] = 0

while stack: #0cost
  p = stack.popleft()
  #print(p)
  dis = vis[p[0]][p[1]]
  for i in range(-2,3):
    for j in range(-2,3):
      if 0<= p[0]+i <H and 0<= p[1]+j <W:
        if maze[p[0]+i][p[1]+j]==".":
          if vis[p[0]+i][p[1]+j]>dis:
            if 0<i*i+j*j<=1:
              vis[p[0]+i][p[1]+j] = dis
              stack.appendleft([p[0]+i,p[1]+j])
            elif i*i+j*j > 1:
              if [p[0]+i,p[1]+j] in stack:
                continue
              vis[p[0]+i][p[1]+j] = dis+1
              stack.append([p[0]+i,p[1]+j])
print(vis[Dh-1][Dw-1])

Submission status: Wrong Answer

Solution code:
import copy
H,W = map(int, input().split())
Ch,Cw = map(int, input().split())
Dh,Dw = map(int, input().split())
maze = []
vis=[]
can = []
stack = [[Ch-1,Cw-1]]
flag = True
for h in range(H):
  maze.append(list(input()))
  vis.append([-1]*W)
vis[Ch-1][Cw-1] = 0

def privis():
  for v in vis:
    print(v)
  print("/n")

while flag:
  canN=[]
  previs = copy.deepcopy(vis)
  while stack: #0cost
    p = stack.pop()
    canN.append(p)
    
    for i in [-1,0,1]:
      for j in [-1,0,1]:
        if 0<= p[0]+i <H and 0<= p[1]+j <W and i*i+j*j==1:
          if maze[p[0]+i][p[1]+j]=="." and not[p[0]+i,p[1]+j] in stack:
            if vis[p[0]+i][p[1]+j]==-1 or vis[p[0]+i][p[1]+j]>vis[p[0]][p[1]]:
              vis[p[0]+i][p[1]+j] = vis[p[0]][p[1]]
              stack.append([p[0]+i,p[1]+j])
  can.append(canN)
  privis()
  
  while canN:
    p = canN.pop()
    for i in range(-2,3):
      for j in range(-2,3):
        if 0<= p[0]+i <H and 0<= p[1]+j <W and i*i+j*j>1:
          if maze[p[0]+i][p[1]+j]=="." and not[p[0]+i,p[1]+j] in stack:
            if vis[p[0]+i][p[1]+j]==-1 or vis[p[0]+i][p[1]+j]>vis[p[0]][p[1]]:
              vis[p[0]+i][p[1]+j] = vis[p[0]][p[1]]+1
              stack.append([p[0]+i,p[1]+j])
  privis()
  if vis[Dh-1][Dw-1]>-1:
    print(vis[Dh-1][Dw-1])
    flag=False