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: Accepted

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 main():
    H, W = i_map()
    Ch, Cw = i_map()
    Dh, Dw = i_map()
    Ch,Cw = Ch-1,Cw-1
    Dh,Dw = Dh-1,Dw-1
    maze = [input() for _ in range(H)]

    INF = 10 ** 12
    path = [[INF] * W for _ in range(H)]  # path: 各マスへの移動コスト

    # walk:移動A, warp:移動B
    walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
    warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]

    q = deque()
    path[Ch][Cw] = 0
    q.append((Ch, Cw, 0))

    while(q):
        ux,uy,s = q.popleft()
        for dx,dy in walk:
            nx = ux + dx
            ny = uy + dy
            if(0<=nx<H and 0<=ny<W and maze[nx][ny]=='.' and path[nx][ny] > s):
                path[nx][ny] = s
                q.appendleft((nx,ny,s))
        for dx,dy in warp:
            nx = ux + dx
            ny = uy + dy
            if(0<=nx<H and 0<=ny<W and maze[nx][ny]=='.' and path[nx][ny] > s+1):
                path[nx][ny] = s+1
                q.append((nx,ny,s+1))

    ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
    print(ans)


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()

from heapq import *

H, W = map(int, input().split())
m1 = lambda s: int(s)-1
sy, sx = map(m1, input().split())
fy, fx = map(m1, input().split())
G = [list(input()) for _ in range(H)]
D = [[10 ** 18] * W for _ in range(H)]

D[sy][sx] = 0
Q = [(0, sx, sy)]
while Q:
	d, x, y = heappop(Q)
	if D[y][x] < d: continue

	if (x, y) == (fx, fy):
		print(d)
		break

	for dx in range(-2, 3):
		for dy in range(-2, 3):
			nx = x + dx
			ny = y + dy
			if nx < 0 or ny < 0 or nx >= W or ny >= H or G[ny][nx] == '#': continue
			nd = d + (0 if abs(dx) + abs(dy) == 1 else 1)
			if nd >= D[ny][nx]: continue
			D[ny][nx] = nd
			heappush(Q, (nd, nx, ny))
else:
	print(-1)

Submission status: Accepted

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('#'*(w+2)) for i in range(h+2)]
for i in range(h):
    a = '#' + input() + '#'
    s[i+1] = list(a)
queue = deque([[ch,cw]])
s[ch][cw] = 0
l = [[0,-1],[0,1],[-1,0],[1,0]] 
r = [[] for i in range(20)]
k = 0
for i in range(-2,3):
    for j in range(-2,3):
        if i != 0 or j != 0:
            if not [i,j] in l:
                r[k] = [i,j]
                k += 1
while queue:
    x,y = queue.popleft()
    if [x,y] != [dh,dw]:
        for n,m in l:
            new_h,new_w = x+n,y+m 
            if s[new_h][new_w] == '.':
                s[new_h][new_w] = s[x][y]
                queue.appendleft([new_h,new_w])
            elif s[new_h][new_w] != "#":
                if s[new_h][new_w] > s[x][y]:
                    s[new_h][new_w] = s[x][y]
                    queue.appendleft([new_h,new_w])
            else:
                pass
        for n,m in r:
            new_h,new_w = x+n,y+m
            if new_h >= 0 and new_h <= h+1 and new_w >= 0 and new_w <= w+1:
                if s[new_h][new_w] == '.':
                    s[new_h][new_w] = s[x][y]+1
                    queue.append([new_h,new_w])
                elif s[new_h][new_w] != "#":
                    if s[new_h][new_w] > s[x][y]+1:
                        s[new_h][new_w] = s[x][y]+1
                        queue.append([new_h,new_w])
                else:
                    pass
if s[dh][dw] != '.':
    print(s[dh][dw])
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque
def solve():  
    h, w = map(int,input().split())
    ch, cw = map(int,input().split())
    Dh, Dw = map(int,input().split())
    
    M = ['##' + input() + '##' for _ in range(h)]
    for i in range(2):
        M.insert(0,'#'*(w+4))
        M.append('#'*(w+4))
    
    INF = float('inf')
    cost = [[INF for _ in range(w+4)] for _ in range(h+4)]
    cost0 = deque()
    ans = -1
    
    cost0.append((ch+1, cw+1, 0))
    cost[ch+1][cw+1] = 0
    
    move = [(1,0),(0,1),(-1,0),(0,-1)]
    warp = [(i,j) for i in range(-2,3) for j in range(-2,3) if (i,j) not in [(0,0)] + move]
    
    cost1 = deque()
    
    while cost0:
        h, w, c = cost0.popleft()
        cost1.append((h, w, c))
        
        for i,j in move:
            dh = h + i
            dw = w + j
            if M[dh][dw] == '.' and c < cost[dh][dw]: #コストが高いところから低いところに戻らないようにするため
                cost[dh][dw] = c
                cost0.appendleft((dh, dw, cost[dh][dw]))
        
        if len(cost0) == 0:
            while cost1:
                h, w, c = cost1.popleft()
                for i,j in warp:
                    dh = h + i
                    dw = w + j
                    if M[dh][dw] == '.' and c+1 < cost[dh][dw]:  #無駄なワープをなくすため
                        cost[dh][dw] = c+1
                        cost0.append((dh, dw, cost[dh][dw]))
        if cost[Dh+1][Dw+1] != INF:
            ans = cost[Dh+1][Dw+1]
    
    print(ans)

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
from collections import deque
 
H, W = map(int, input().split())
Ch, Cw = map(lambda x: int(x) - 1, input().split())
Dh, Dw = map(lambda x: int(x) - 1, input().split())
maze = [input() for _ in range(H)]
 
INF = 10 ** 12
path = [[INF] * W for _ in range(H)]  # path: 各マスへの移動コスト
 
walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]
 
q = deque()
path[Ch][Cw] = 0
q.append((Ch, Cw, 0))
 
while q:
    x, y, s = q.popleft()
    for dx, dy in walk:  # 移動A
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s:
            path[nx][ny] = s
            q.appendleft((nx, ny, s))  # 移動Aの場合はコスト0. キューの先頭に追加する.
    for dx, dy in warp:  # 移動B
        nx = x + dx
        ny = y + dy
        if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] == '.' and path[nx][ny] > s + 1:
            path[nx][ny] = s + 1
            q.append((nx, ny, s + 1))  # 移動Bの場合はコスト1. キューの最後尾に追加する.
    
ans = path[Dh][Dw] if path[Dh][Dw] < INF else '-1'
print(ans)

Submission status: Accepted

Solution code:

from collections import deque

H, W = map(int, input().split())
sx, sy = map(int, input().split())
gx, gy = map(int, input().split())
sx -= 1
sy -= 1
gx -= 1
gy -= 1

C = [list(input()) for i in range(H)]
inf = float("inf")
for i in range(H):
    for j in range(W):
        if C[i][j] == ".":
            C[i][j] = 0
        else:
            C[i][j] = 1
d0 = [[1, 0], [0, 1], [-1, 0], [0, -1]]
d1 = [[-2, -2], [-2, -1], [-2, 0], [-2, 2], [-1, 2], [0, 2], [-2, 1], [-1, -2], [-1, -1], [-1, 1], [0, -2], [1, -2], [1, -1], [1, 1], [1, 2], [2, -2], [2, -1], [2, 0], [2, 1], [2, 2]]
# d1 = [[i, j] for i in range(-2, 3) for j in range(-2, 2)]
dist = [[inf] * W for i in range(H)]
dist[sx][sy] = 0
que = deque([[0, sx, sy]])
while que:
    L, x, y = que.popleft()
    # if x == gx and y == gy:
    #     break
    for dx, dy in d0:
        nx, ny = x + dx, y + dy
        if 0 <= nx < H and 0 <= ny < W and L + C[nx][ny] < dist[nx][ny] and C[nx][ny] == 0:
            dist[nx][ny] = L + C[nx][ny]
            que.appendleft([L, nx, ny])
    for dx, dy in d1:
        nx, ny = x + dx, y + dy
        if 0 <= nx < H and 0 <= ny < W and L + C[nx][ny] + 1 < dist[nx][ny] and C[nx][ny] == 0:
            dist[nx][ny] = L + C[nx][ny] + 1
            que.append([L + 1, nx, ny])


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

Submission status: Accepted

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()

  print(C[-~dy][-~dx])

if __name__ == "__main__":
  main()

Submission status: Accepted

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))

  print(C[-~dy][-~dx])

if __name__ == "__main__":
  main()

Submission status: Accepted

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 = [[False]*W for _ in range(H)]
for h in range(H):
    s = input()
    for w in range(W):
        if s[w] == ".":
            S[h][w] = True
d = [[10**9]*W for _ in range(H)]
d[Ch-1][Cw-1] = 0

D = deque([(Ch-1, Cw-1, 0)])
while D:
    h, w, c = deque.popleft(D)
    if c > d[h][w]:
        continue
    # 歩いて移動
    # 上
    if h > 0:
        if S[h-1][w] and c < d[h-1][w]:
            d[h-1][w] = c
            deque.appendleft(D, (h-1, w, c))
    # 下
    if h < H-1:
        if S[h+1][w] and c < d[h+1][w]:
            d[h+1][w] = c
            deque.appendleft(D, (h+1, w, c))
    # 左
    if w > 0:
        if S[h][w-1] and c < d[h][w-1]:
            d[h][w-1] = c
            deque.appendleft(D, (h, w-1, c))
    # 右
    if w < W-1:
        if S[h][w+1] and c < d[h][w+1]:
            d[h][w+1] = c
            deque.appendleft(D, (h, w+1, c))
    # ワープで移動
    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, c+1))
if d[Dh-1][Dw-1] == 10**9:
    print(-1)
else:
    print(d[Dh-1][Dw-1])

Submission status: Accepted

Solution code:
# D - Wizard in Maze

h,  w  = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
s = []
for i in range(h):
    s.append([c for c in input()])

queue = [[(ch - 1, cw - 1)], []]

dist = 0
while len(queue[0]) > 0:
    while len(queue[0]) > 0:
        y, x = queue[0].pop()
        if s[y][x] != '.':
            continue
        s[y][x] = dist
        for vy in range(-2, 3):
            for vx in range(-2, 3):
                if 0 <= y + vy < h and 0 <= x + vx < w and \
                   s[y + vy][x + vx] == '.':
                    cost = 0 if abs(vx) + abs(vy) <= 1 else 1
                    queue[cost].append((y + vy, x + vx))
    dist += 1
    queue = [queue[1], queue[0]]

dist = s[dh - 1][dw - 1]
print(dist if dist != '.' else -1)

Submission status: Accepted

Solution code:
# D - Wizard in Maze

from collections import deque

h,  w  = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
s = []
for i in range(h):
    s.append([c for c in input()])

def dfs(y, x, area_id):
    stack = [(y, x)]
    while len(stack) > 0:
        y, x = stack.pop()
        if s[y][x] == '.':
            s[y][x] = area_id
            for vy, vx in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
                if (0 <= x + vx < w and 0 <= y + vy < h and
                    s[y + vy][x + vx] == '.'):
                    stack.append((y + vy, x + vx))

n_area = 0
for y in range(h):
    for x in range(w):
        if s[y][x] == '.':
            dfs(y, x, n_area)
            n_area += 1

# links between areas
adj = [set() for i in range(n_area)]
for y in range(h):
    for x in range(w):
        if s[y][x] == '#':
            continue
        for vy in range(0, 3):
            for vx in range(-2, 3):
                if (0 <= x + vx < w and 0 <= y + vy < h and
                    s[y + vy][x + vx] != '#'):
                    adj[s[y][x]].add(s[y + vy][x + vx])
                    adj[s[y + vy][x + vx]].add(s[y][x])

c = s[ch - 1][cw - 1]
d = s[dh - 1][dw - 1]
dist = [float('inf') for i in range(n_area)]
dist[c] = 0

q = deque()
q.append((c, 0))
while len(q) > 0:
    c, cost = q.popleft()
    for x in adj[c]:
        if dist[x] > cost + 1:
            dist[x] = cost + 1
            q.append((x, cost + 1))

print(dist[d] if dist[d] < float('inf') else -1)

Submission status: Accepted

Solution code:
def walk(h, w, maze, que, step):
    search_area = ((h, w - 1), (h, w + 1), (h - 1, w), (h + 1, w))
    for i in range(4):
        search_cell = search_area[i]
        condition1 = search_cell[0] in range(H)
        condition2 = search_cell[1] in range(W)
        if condition1 and condition2:
            if maze[search_cell[0]][search_cell[1]] == '.':
                que.append(search_cell)
                maze[search_cell[0]][search_cell[1]] = step


def warp(h, w, maze, que, step):
    for i in range(-2, 3):
        for j in range(-2, 3):
            search_cell = (h + i, w + j)
            condition1 = search_cell[0] in range(H)
            condition2 = search_cell[1] in range(W)
            if condition1 and condition2:
                if maze[search_cell[0]][search_cell[1]] == '.':
                    que.append(search_cell)
                    maze[search_cell[0]][search_cell[1]] = step


H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())
maze = [list(input()) for _ in range(H)]
                    
ques = [[(Ch - 1, Cw - 1)]]  # list of list of tuples
step = 0

i = 0
while True:
    try:
        walk(h=ques[step][i][0], w=ques[step][i][1], maze=maze, que=ques[step], step=step)
        i += 1
    except:
        step += 1
        ques.append([])
        break

while True:
    for cell in ques[step - 1]:
        warp(h=cell[0], w=cell[1], maze=maze, que=ques[step], step=step)
    if ques[step] == []:
        break
    else:
        i = 0
        while True:
            try:
                walk(h=ques[step][i][0], w=ques[step][i][1], maze=maze, que=ques[step], step=step)
                i += 1
            except:
                step += 1
                ques.append([])
                break

if type(maze[Dh - 1][Dw - 1]) == int:
  print(maze[Dh - 1][Dw - 1])
else:
  print(-1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque
from math import inf


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


def bfs(maze, Ch, Cw, Dh, Dw, H, W):
    visited = [[inf] * W for i in range(H)]
    queue = deque([[Ch, Cw]])
    visited[Ch][Cw] = 0

    dy_dx0 = [[0, 1], [1, 0], [0, -1], [-1, 0]]
    dy_dx1 = [[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]]

    while queue:
        y, x = queue.popleft()
        if [y, x] == [Dh, Dw]:
            break
        for j, k in dy_dx0:
            new_y, new_x = y + j, x + k
            if 0 <= new_y < H and 0 <= new_x < W and maze[new_y][new_x] == "." and visited[y][x] < visited[new_y][new_x]:
                visited[new_y][new_x] = visited[y][x]
                queue.appendleft([new_y, new_x])
        for j, k in dy_dx1:
            new_y, new_x = y + j, x + k
            if 0 <= new_y < H and 0 <= new_x < W and maze[new_y][new_x] == "." and visited[new_y][new_x] == inf:
                visited[new_y][new_x] = visited[y][x] + 1
                queue.append([new_y, new_x])
    return visited[Dh][Dw]


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

    dist = bfs(maze, Ch - 1, Cw - 1, Dh - 1, Dw - 1, H, W)

    print(dist if dist != inf else -1)


if __name__ == "__main__":
    main()

Submission status: Accepted

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.appendleft([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: Accepted

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 = [list(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, py) == (Dh, 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.appendleft((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))

    # for a in visit:
    #     print(a)

print(-1)

Submission status: Accepted

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)]
INF=10**7

queue = deque()

cost = [[INF]*w for _ in range(h)]
cost[ch-1][cw-1]=0

dxdy = [[1,0],[-1,0],[0,1],[0,-1]]
warp = []
for m in range(-2,3):
    for n in range(-2,3):
        if [m,n] not in [[0,0],[1,0],[-1,0],[0,1],[0,-1]]:
            warp += [[m,n]]

queue.append([ch-1,cw-1,0])

while queue:
    x,y,d = queue.popleft()
    if d>cost[x][y]:
        continue
    for dx,dy in dxdy:
        nx,ny = x+dx,y+dy
        if -1<nx<h and -1<ny<w and s[nx][ny]!="#" and d<cost[nx][ny]:
            cost[nx][ny]=d
            queue.appendleft([nx,ny,d])

    for dx,dy in warp:
        nx,ny = x+dx,y+dy
        if -1<nx<h and -1<ny<w and s[nx][ny]!="#" and d+1<cost[nx][ny]:            
            cost[nx][ny]=d+1
            queue.append([nx,ny,d+1])

if cost[dh-1][dw-1]<INF:
    print(cost[dh-1][dw-1])
else:
    print(-1)

Submission status: Accepted

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

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)]
INF=10**7

queue = deque()

cost = [[INF]*w for _ in range(h)]
cost[ch-1][cw-1]=0

dxdy = [[1,0],[-1,0],[0,1],[0,-1]]
warp = []
for m in range(-2,3):
    for n in range(-2,3):
        if [m,n] not in [[0,0],[1,0],[-1,0],[0,1],[0,-1]]:
            warp += [[m,n]]

queue.append([ch-1,cw-1,0])

while queue:
    x,y,d = queue.popleft()
    if d>cost[x][y]:
        continue
    for dx,dy in dxdy:
        nx,ny = x+dx,y+dy
        if -1<nx<h and -1<ny<w and s[nx][ny]!="#" and d<cost[nx][ny]:
            cost[nx][ny]=d
            queue.appendleft([nx,ny,d])

    for dx,dy in warp:
        nx,ny = x+dx,y+dy
        if -1<nx<h and -1<ny<w and s[nx][ny]!="#" and d+1<cost[nx][ny]:            
            cost[nx][ny]=d+1
            queue.append([nx,ny,d+1])

if cost[dh-1][dw-1]<INF:
    print(cost[dh-1][dw-1])
else:
    print(-1)

Submission status: Accepted

Solution code:
from random import randrange

import sys
input = sys.stdin.readline
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)]
# h,w=1000,1000
# ch,cw=3,3
# dh,dw=8,8
# s=[]
# for _ in range(h):
#     row=[]
#     for j in range(w):
#         row.append("#."[randrange(2)])
#     s.append(row)
# s[ch-1][cw-1]="."
# s[dh-1][dw-1]="."
# for row in s:print(row)

INF=10**7

queue = deque()

cost = [[INF]*w for _ in range(h)]
cost[ch-1][cw-1]=0

dxdy = [[1,0],[-1,0],[0,1],[0,-1]]
warp = []
for m in range(-2,3):
    for n in range(-2,3):
        if [m,n] not in [[0,0],[1,0],[-1,0],[0,1],[0,-1]]:
            warp += [[m,n]]

queue.append([ch-1,cw-1,0])

while queue:
    x,y,d = queue.popleft()
    # if d>cost[x][y]:continue
    for dx,dy in dxdy:
        nx,ny = x+dx,y+dy
        if -1<nx<h and -1<ny<w and s[nx][ny]!="#" and d<cost[nx][ny]:
            cost[nx][ny]=d
            queue.appendleft([nx,ny,d])
            #[print(*cost[l]) for l in range(h)]
            #print("---------------")

    for dx,dy in warp:
        nx,ny = x+dx,y+dy
        if -1<nx<h and -1<ny<w and s[nx][ny]!="#" and d+1<cost[nx][ny]:
            cost[nx][ny]=d+1
            queue.append([nx,ny,d+1])
            #[print(*cost[l]) for l in range(h)]
            #print("---------------")


if cost[dh-1][dw-1]<INF:
    print(cost[dh-1][dw-1])
else:
    print(-1)

Submission status: Accepted

Solution code:
"""
01BFS: ステップ数が多ければ後ろに持っていく
"""
def main():
    from collections import deque
    H,W = map(int,input().split())
    Ch,Cw = map(int,input().split())
    Dh,Dw = map(int,input().split())
    maze = [list(input()) for _ in range(H)]

    que = deque([(Ch-1,Cw-1,0)])
    adjectns = [(1,0),(0,1),(-1,0),(0,-1)]
    for _ in range(100000000):
        if not que:
            break
        h,w,step = que.popleft()
        if h == Dh-1 and w == Dw-1:
            print(step)
            exit()
        else:
            if maze[h][w] == ".":
                maze[h][w] = step
                for a,b in adjectns:
                    x = h + a
                    y = w + b
                    if 0<=x<H and 0<=y<W and maze[x][y]==".":
                        que.appendleft((x,y,step))
                for i in range(-2,3):
                    for j in range(-2,3):
                        x = h+i
                        y = w+j
                        if 0<=x<H and 0<=y<W and maze[x][y]==".":
                            que.append((x,y,step+1))
    print(-1)
main()

Submission status: Accepted

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

s = []
for i in range(h):
  t = input()
  s.append(t)

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

queue = deque([[ch,cw]])
visited = [[1000000 for i in range(w)] for j in range(h)]
visited[ch][cw] = 0
while queue:
  l,m = queue.popleft()
  d = visited[l][m]
  for k in range(4):
    x = l + dx[k]
    y = m + dy[k]
    if x < 0 or y < 0 or x >= h or y >= w or visited[x][y] <= d or s[x][y] == "#":
      continue
    visited[x][y] = d
    queue.appendleft([x,y])
  for i in range(-2,3):
    for j in range(-2,3):
      if (i== 1 and j == 0)or(i==-1 and j == 0)or(i==0 and j == 1)or(i==0 and j==-1)or(i==0 and j==0):
        continue
      x = l + i
      y = m + j
      if x < 0 or y < 0 or x >= h or y >= w or visited[x][y] <= d+1 or s[x][y] == "#":
        continue
      visited[x][y] = d + 1
      queue.append([x,y])
  #print (queue)
if visited[dh][dw] == 1000000:
  print (-1)
else:
  print (visited[dh][dw])

Submission status: Accepted

Solution code:
from sys import stdin
from queue import Queue
from math import ceil
inp = lambda : stdin.readline().strip()

X = [0,1,0,-1]
Y = [-1,0,1,0]
def isValid(x,y):
    if x >= 0 and y >= 0 and x < h  and y < w:
        return True
    return False


def dfs_iter(x,y):
    stack = [(x,y)]
    while stack:
        x,y = stack.pop()
        if isValid(x,y) and visited[x][y] == -1 and  maze[x][y] != '#':
            visited[x][y] = curr
            for i,j in zip(X,Y):
                if isValid(x+i,y+j) and visited[x+i][y+j] == -1  and maze[x+i][y+j] != '#':
                    stack.append((x+i,y+j))
def bfs(n):
    stack = Queue()
    stack.put(n)
    depths = Queue()
    depths.put(0)
    ans = 10**9 + 7
    while not stack.empty():
        node = stack.get()
        depth = depths.get()
        if not visited2[node]:
            visited2[node] = True
            if node == visited[dh-1][dw-1]:
                ans = min(ans,depth)
            for child in adj[node]:
                if not visited2[child]:
                    stack.put(child)
                    depths.put(depth+1)
    if ans == 10**9 + 7:
        return -1
    return ans


h, w = [int(x) for x in inp().split()]
ch,cw = [int(x) for x in inp().split()]
dh, dw = [int(x) for x in inp().split()]
visited  = [[-1]*w for x in range(h)]

maze = []
adj = [set() for i in range(ceil(h*w/2))]
visited2 = [False]*(ceil(h*w/2))
for i in range(h):
    maze.append(list(inp()))

curr = 0
ans = []
for i in range(h):
    for j in range(w):
        if visited[i][j] == -1 and maze[i][j] != '#':
            dfs_iter(i,j)
            curr += 1
for i in range(h):
    for j in range(w):
        if maze[i][j] != '#':
            for k in range(-2,3):
                for l in range(-2,3):
                    if not (k==l and l == 0):
                        if isValid(i+k,j + l) and visited[i][j] != visited[i+k][j+l] and maze[i+k][j+l] != '#':
                            adj[visited[i][j]].add(visited[i+k][j+l])

print(bfs(visited[ch-1][cw-1]))

Submission status: Accepted

Solution code:
from collections import deque



R, C = map(int, input().split())
sy, sx = map(int, input().split())
gy, gx = map(int, input().split())

sy, sx, gy, gx = sy-1, sx-1, gy-1, gx-1
maze = [list(input()) for i in range(R)]
d = deque()
ds = deque()
maze[sy][sx] = 0
d.append([sy, sx])
ds.append([sy, sx])
while(d or ds):
  while(d):
    [y, x] = d.popleft()
    ds.append([y, x])
    if (y, x) == (gy, gx):
      print(maze[gy][gx])
      exit()
    for [dy, dx] in [[1,0], [-1,0], [0,1], [0,-1]]:
      ny = y + dy
      nx = x + dx
      if  R > ny and ny >= 0 and C > nx and nx >= 0 and maze[ny][nx] == ".":
        maze[ny][nx] = maze[y][x]
        d.append([ny, nx])
        ds.append([ny, nx])

  while(ds):   
    [y, x] = ds.popleft()
    for [dy, dx] in [[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]]:
      ny = y + dy
      nx = x + dx
      if  R > ny and ny >= 0 and C > nx and nx >= 0 and maze[ny][nx] == ".":
        maze[ny][nx] = maze[y][x]+1
        d.append([ny,nx])
        
        
print(-1)