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:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

INF = 10**9
dst = [[INF]*W for _ in range(H)]
dst[sh][sw] = 0

from collections import deque
dq = deque([(sh, sw)])
while dq:
    h, w = dq.popleft()

    for dh, dw in dhw[:4]:
        nh = h + dh; nw = w + dw
        if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and dst[h][w] < dst[nh][nw]:
            dst[nh][nw] = dst[h][w]
            dq.appendleft((nh, nw))

    for dh, dw in dhw[4:]:
        nh = h + dh; nw = w + dw
        if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and dst[h][w] + 1 < dst[nh][nw]:
            dst[nh][nw] = dst[h][w] + 1
            dq.append((nh, nw))

print(-1 if dst[eh][ew]==INF else dst[eh][ew])

Submission status: Accepted

Solution code:
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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

INF = 10**9
dst = [[INF]*W for _ in range(H)]
dst[sh][sw] = 0

from collections import deque
dq = deque([(sh, sw)])
while dq:
    h, w = dq.popleft()

    for dh, dw in walk:
        nh = h + dh; nw = w + dw
        if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and dst[h][w] < dst[nh][nw]:
            dst[nh][nw] = dst[h][w]
            dq.appendleft((nh, nw))

    for dh, dw in warp:
        nh = h + dh; nw = w + dw
        if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == '.' and dst[h][w] + 1 < dst[nh][nw]:
            dst[nh][nw] = dst[h][w] + 1
            dq.append((nh, nw))

print(-1 if dst[eh][ew]==INF else dst[eh][ew])

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
ch, cw = map(int, input().split())
gh, gw = map(int, input().split())

ch += 1
cw += 1
gh += 1
gw += 1

maze = ["#"*(W+4), "#"*(W+4)] + ["##" + input() + "##" for _ in range(H)] + ["#"*(W+4), "#"*(W+4)]
visited = [[-1]*(W+4) for _ in range(H+4)]
visited[ch][cw] = 0

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

queue = deque([[ch, cw]])

while queue:
    h, w = queue.popleft()
    for dh, dw in walk:
        h_next = h + dh
        w_next = w + dw
        if maze[h_next][w_next]==".":
            if visited[h_next][w_next]==-1 or visited[h_next][w_next] > visited[h][w]:
                visited[h_next][w_next] = visited[h][w]
                queue.appendleft([h_next, w_next])
    
    for dh, dw in warp:
        h_next = h + dh
        w_next = w + dw
        if maze[h_next][w_next]=="." and visited[h_next][w_next]==-1:
            visited[h_next][w_next] = visited[h][w] + 1
            queue.append([h_next, w_next])

print(visited[gh][gw])

Submission status: Accepted

Solution code:
H, W, ch, cw, dh, dw, *S = open(0).read().split()
H, W, ch, cw, dh, dw = [int(_) - 1 for _ in [H, W, ch, cw, dh, dw]]
H += 1
W += 1

stack = [[ch, cw]]
d = 0
INF = 10**10
dists = [[INF] * W for _ in range(H)]
dists[ch][cw] = 0


def valid(x, y):
    return 0 <= x < H and 0 <= y < W


while stack:
    se = set()
    while stack:
        x, y = stack.pop()
        for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            nx, ny = x + dx, y + dy
            if valid(nx, ny) and dists[nx][ny] == INF:
                if S[nx][ny] == '.':
                    dists[nx][ny] = d
                    stack += [[nx, ny]]
                else:
                    se.add((x, y))
    stack2 = []
    d += 1
    for x, y in se:
        for dx in range(-2, 3):
            for dy in range(-2, 3):
                nx, ny = x + dx, y + dy
                if valid(nx, ny) and dists[nx][ny] == INF and S[nx][ny] == '.':
                    stack2 += [[nx, ny]]
                    dists[nx][ny] = d
    stack = stack2

ans = dists[dh][dw]
print(ans if ans < INF else -1)

Submission status: Accepted

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]
dst[sh][sw] = 0

from collections import deque
dq = deque([[sh, sw]])
while dq:
    h, w = dq.popleft()

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] == -1 or dst[h][w] < dst[nh][nw]:
            dst[nh][nw] = dst[h][w]
            dq.appendleft([nh, nw])

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        if dst[nh][nw] == -1 or dst[h][w] + 1 < dst[nh][nw]:
            dst[nh][nw] = dst[h][w] + 1
            dq.append([nh, nw])

print(dst[eh][ew])

Submission status: Accepted

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]
dst[sh][sw] = 0

from collections import deque
dq = deque([(sh, sw)])
while dq:
    h, w = dq.popleft()

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] == -1 or dst[h][w] < dst[nh][nw]:
            dst[nh][nw] = dst[h][w]
            dq.appendleft((nh, nw))

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        if dst[nh][nw] == -1 or dst[h][w] + 1 < dst[nh][nw]:
            dq.append((nh, nw))
            dst[nh][nw] = dst[h][w] + 1

print(dst[eh][ew])

Submission status: Accepted

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]
dst[sh][sw] = 0

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()

    for i in range(4):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] == -1 or d < dst[nh][nw]:
            dq.appendleft((nh, nw, d))
            dst[nh][nw] = d

    for i in range(4, 24):
        nh = h + dhw[i][0]; nw = w + dhw[i][1]
        if nh < 0 or H <= nh : continue
        if nw < 0 or W <= nw : continue
        if S[nh][nw] == '#': continue
        if dst[nh][nw] >= 0: continue
        if dst[nh][nw] == -1 or d + 1 < dst[nh][nw]:
            dq.append((nh, nw, d + 1))
            dst[nh][nw] = d + 1

print(dst[eh][ew])

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

d = [[-1]*W for _ in range(H)]

que = deque([[cw, ch, 0]])
while que:
    x, y, cost = que.popleft()
    if d[y][x]==-1 or d[y][x]>cost:
        d[y][x] = cost
        for dx in range(-2, 3):
            for dy in range(-2, 3):
                nx, ny = x+dx, y+dy
                if 0<=nx<W and 0<=ny<H and s[ny][nx]!='#':
                    if abs(dx)+abs(dy) == 1:
                        que.appendleft([nx, ny, cost])
                    else:
                        que.append([nx, ny, cost+1])  
print(d[dh][dw])

Submission status: Accepted

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()
    if h == eh and w == ew:
        dst[h][w] = d
        break
    if 0 <= h < H and 0 <= w < W and dst[h][w] < 0 and S[h][w] != '#':
        dst[h][w] = d
        for i in range(4): dq.appendleft((h + dhw[i][0], w + dhw[i][1], d))
        for i in range(4, 24): dq.append((h + dhw[i][0], w + dhw[i][1], d+1))

print(dst[eh][ew])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

from collections import deque

q = 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

# mylist = [[]]
ban_list = [[-1 for j in range(w)] for i in range(h)]
cost_list = [[-1 for j in range(w)] for i in range(h)]

# print(mylist)

for i in range(h):
  # 文字列の入力
  s = input()
  for j in range(len(s)):
    ban_list[i][j] = s[j]

ban_list[ch][cw] = 0
# cost_list[ch][cw] = 0

cost = 0
ph = ch
pw = cw

q.append([ph, pw])


# # 最後デバッグ
# for li in ban_list:
#   print(li)



loop = True
while loop:
  # print(len(q))
  ph, pw = q.popleft()
  cost = ban_list[ph][pw]

  # print(ph, pw)
  # print(cost)
  # 上
  if ph == 0:
    pass
  else:
    if ban_list[ph-1][pw] != "#" and ban_list[ph-1][pw] != cost:
      if ban_list[ph-1][pw] == "." or cost < ban_list[ph-1][pw]:
        ban_list[ph-1][pw] = cost
        # appendだとrandom_02.txtがWAになる
        q.appendleft([ph-1, pw])
    else:
      pass

  # 右
  if pw == w -1:
    pass
  else:
    if ban_list[ph][pw + 1] != "#" and ban_list[ph][pw + 1] != cost:
      if ban_list[ph][pw + 1] == "." or cost < ban_list[ph][pw + 1]:
        ban_list[ph][pw + 1] = cost
        q.appendleft([ph, pw+1])
    else:
      pass

  # 下
  if ph == h -1:
    pass
  else:
    if ban_list[ph+1][pw] != "#" and ban_list[ph+1][pw] != cost:
      if ban_list[ph+1][pw] == "." or cost < ban_list[ph+1][pw]:
        ban_list[ph+1][pw] = cost
        q.appendleft([ph+1, pw])
    else:
      pass

  # 左
  if pw == 0:
    pass
  else:
    if ban_list[ph][pw - 1] != "#" and ban_list[ph][pw - 1] != cost:
      if ban_list[ph][pw - 1] == "." or cost < ban_list[ph][pw - 1]:
        ban_list[ph][pw - 1] = cost
        q.appendleft([ph, pw-1])
    else:
      pass


  # ジャンプ--------------
  for i in range(-2, 3):
    if (ph + i < 0) or (h - 1 < ph + i):
      continue

    for j in range(-2, 3):
      if (pw + j < 0) or (w - 1 < pw + j) or (i==0 and j == 0) or (i==0 and j == -1) or (i==0 and j == 1) or (i==-1 and j == 0) or (i==1 and j == 0):
        continue
      if ban_list[ph + i][pw + j] == ".":
        # print(ph, pw)
        # print(i, j)
        # print(cost)
        ban_list[ph + i][pw + j] = cost + 1
        q.append([ph + i, pw + j])

  if len(q) == 0:
    loop = False


result = ban_list[dh][dw]
if result == ".":
  result = -1

# # 最後デバッグ
# for li in ban_list:
#   print(li)

print(result)

Submission status: Accepted

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()
    if 0 <= h < H and 0 <= w < W and dst[h][w] < 0 and S[h][w] != '#':
        dst[h][w] = d
        for i in range(4): dq.appendleft((h + dhw[i][0], w + dhw[i][1], d))
        for i in range(4, 24): dq.append((h + dhw[i][0], w + dhw[i][1], d+1))

print(dst[eh][ew])

Submission status: Accepted

Solution code:
dhw = [(1,0),(0,-1),(0,1),(-1,0),
( 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)]

H, W = map(int, input().split())
sh, sw = map(lambda x:int(x)-1, input().split())
eh, ew = map(lambda x:int(x)-1, input().split())
S = [input() for _ in range(H)]

dst = [[-1]*W for _ in range(H)]

from collections import deque
dq = deque([(sh, sw, 0)])
while dq:
    h, w, d = dq.popleft()
    if h < 0 or H <= h or w < 0 or W <= w or dst[h][w] >= 0 or S[h][w] == '#': continue
    dst[h][w] = d
    for i in range(4): dq.appendleft((h + dhw[i][0], w + dhw[i][1], d))
    for i in range(4, 24): dq.append((h + dhw[i][0], w + dhw[i][1], d+1))

print(dst[eh][ew])

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())
maze = [[9]*(w+4)]
maze.append([9]*(w+4))
for i in range(h):
  s = input()
  tmp = [9,9]
  for i in s:
    if i == "#":
      tmp.append(9)
    else:
      tmp.append(0)
  tmp.append(9)
  tmp.append(9)
  maze.append(tmp)
maze.append([9]*(w+4))
maze.append([9]*(w+4))
#print(maze)

pos = deque()
pos.append([ch+1,cw+1,0])
while len(pos)>0:
  x, y, hop = pos.popleft()
  #print(pos)
  #print[x,y,hop)
  if (x,y) == (dh+1,dw+1):
    print(hop)
    break
  maze[x][y] = 3
  
  if maze[x-1][y] <3:
    pos.appendleft([x-1,y,hop])
    maze[x-1][y] = 3  
    
  if maze[x+1][y] <3:
    pos.appendleft([x+1,y,hop])
    maze[x+1][y] = 3
    
  if maze[x][y-1] <3:
    pos.appendleft([x,y-1,hop])
    maze[x][y-1] = 3
    
  if maze[x][y+1] <3:
    pos.appendleft([x,y+1,hop])
    maze[x][y+1] = 3

  #move =[(-2,0),(-2,1),(-2,2),(-2,-1),(-2,-2),(2,0),(2,1),(2,2),(2,-1),(2,-2),(0,-2),(-1,-2),(1,-2),(0,2),(-1,2),(1,2),(-1,1),(-1,-1),(1,1),(1,-1)]
  move = [(i,j) for i in range(-2,3) for j in range(-2,3)]
  for dx,dy in move:
    if maze[x+dx][y+dy] <2:
      pos.append([x+dx,y+dy,hop+1])
      maze[x+dx][y+dy] = 2
  
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())
maze = [[9]*(w+4)]
maze.append([9]*(w+4))
for i in range(h):
  s = input()
  tmp = [9,9]
  for i in s:
    if i == "#":
      tmp.append(9)
    else:
      tmp.append(0)
  tmp.append(9)
  tmp.append(9)
  maze.append(tmp)
maze.append([9]*(w+4))
maze.append([9]*(w+4))
#print(maze)

pos = deque()
pos.append([ch+1,cw+1,0])
while len(pos)>0:
  x, y, hop = pos.popleft()
  #print(pos)
  #print[x,y,hop)
  if (x,y) == (dh+1,dw+1):
    print(hop)
    break
  maze[x][y] = 3
  
  if maze[x-1][y] <3:
    pos.appendleft([x-1,y,hop])
    maze[x-1][y] = 3  
    
  if maze[x+1][y] <3:
    pos.appendleft([x+1,y,hop])
    maze[x+1][y] = 3
    
  if maze[x][y-1] <3:
    pos.appendleft([x,y-1,hop])
    maze[x][y-1] = 3
    
  if maze[x][y+1] <3:
    pos.appendleft([x,y+1,hop])
    maze[x][y+1] = 3

  move =[(-2,0),(-2,1),(-2,2),(-2,-1),(-2,-2),(2,0),(2,1),(2,2),(2,-1),(2,-2),(0,-2),(-1,-2),(1,-2),(0,2),(-1,2),(1,2),(-1,1),(-1,-1),(1,1),(1,-1)]
  for dx,dy in move:
    if maze[x+dx][y+dy] <2:
      pos.append([x+dx,y+dy,hop+1])
      maze[x+dx][y+dy] = 2
  
else:
  print(-1)

Submission status: Accepted

Solution code:
from sys import *
from collections import deque
H, W = map(int, stdin.readline().split())
personY, personX = map(int, stdin.readline().split())
gH, gW = map(int, stdin.readline().split())

grid = [input() for x in range(H)]
visited = [[10**10] * W for i in range(H)]
options = deque([[personY-1, personX-1]])

visited[personY-1][personX-1] = 0
while(options):
    y,x = options.popleft()
    if y+1 < H and  grid[y+1][x] == ".":
        if visited[y+1][x] > visited[y][x]:
            options.appendleft((y+1, x))
            visited[y+1][x] = visited[y][x]

    if  y-1 >= 0 and grid[y-1][x] == ".":
        if visited[y-1][x] > visited[y][x]:
            options.appendleft((y-1, x))
            visited[y-1][x] = visited[y][x]

    if x+1 < W and grid[y][x+1] == ".":
        if visited[y][x+1] > visited[y][x]:
            options.appendleft((y, x+1))
            visited[y][x+1] = visited[y][x]

    if x-1 >= 0 and grid[y][x-1] == ".":
        if visited[y][x-1] > visited[y][x]:
            options.appendleft((y, x-1))
            visited[y][x-1] = visited[y][x]
   #-------------------------------------------
    for Y,X 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)]:
       if x+X >= 0 and x+X < W and y+Y >= 0 and y+Y < H and grid[y+Y][x+X] == ".":
           if visited[y+Y][x+X] > visited[y][x] +1:
               options.append((y+Y, x+X))
               visited[y+Y][x+X] = visited[y][x]+1

print(-1 if visited[gH-1][gW-1] == 10**10 else visited[gH-1][gW-1] )

Submission status: Accepted

Solution code:
from sys import *
from collections import deque
H, W = map(int, stdin.readline().split())
personY, personX = map(int, stdin.readline().split())
gH, gW = map(int, stdin.readline().split())

grid = [list(stdin.readline().strip()) for x in range(H)]
visited = [ [10**10] * W for i in range(H)]
options = deque([[personY-1, personX-1]])

visited[personY-1][personX-1] = 0
while(options):
    y,x = options.popleft()
    if y+1 < H and  grid[y+1][x] == ".":
        if visited[y+1][x] > visited[y][x]:
            options.appendleft((y+1, x))
            visited[y+1][x] = visited[y][x]

    if  y-1 >= 0 and grid[y-1][x] == ".":
        if visited[y-1][x] > visited[y][x]:
            options.appendleft((y-1, x))
            visited[y-1][x] = visited[y][x]

    if x+1 < W and grid[y][x+1] == ".":
        if visited[y][x+1] > visited[y][x]:
            options.appendleft((y, x+1))
            visited[y][x+1] = visited[y][x]

    if x-1 >= 0 and grid[y][x-1] == ".":
        if visited[y][x-1] > visited[y][x]:
            options.appendleft((y, x-1))
            visited[y][x-1] = visited[y][x]
   #-------------------------------------------
    for Y,X 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)]:
       if x+X >= 0 and x+X < W and y+Y >= 0 and y+Y < H and grid[y+Y][x+X] == ".":
           if visited[y+Y][x+X] > visited[y][x] +1:
               options.append((y+Y, x+X))
               visited[y+Y][x+X] = visited[y][x]+1

print(-1 if visited[gH-1][gW-1] == 10**10 else visited[gH-1][gW-1] )

Submission status: Accepted

Solution code:
from collections import *

def main():
    H,W = map(int, input().split())
    ch,cw = map(int, input().split())
    dh,dw = map(int, input().split())
    s = ["#"*(W+4)]
    s.append("#"*(W+4))
    for i in range(H):
        s.append("##"+input()+"##")
    s.append("#"*(W+4))
    s.append("#"*(W+4))
    
    ans = [[-1]*(W+4) for _ in range(H+4)]
    for i in range(H+4):
        for j in range(W+4):
            if s[i][j] == "#":
                ans[i][j] = -2
    ch += 1; cw += 1
    dh += 1; dw += 1
    ans[ch][cw] = 0
    
    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]]
    
    mylist = deque([[ch,cw]])
    mylist2 = deque([])
    while len(mylist) > 0:
        x,y = mylist.popleft()
        mylist2.append([x,y])
        for p,q in move:
            v1,v2 = x+p,y+q
            if ans[v1][v2] == -1:
                mylist.append([v1,v2])
                ans[v1][v2] = ans[x][y]
        if len(mylist) == 0:
            while len(mylist2) > 0:
                x2,y2 = mylist2.popleft()
                for v1,v2 in magic:
                    i,j = x2+v1,y2+v2
                    if ans[i][j] == -1:
                        ans[i][j] = ans[x2][y2]+1
                        mylist.append([i,j])
    print(ans[dh][dw])
 
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import *

def main():
    H,W = map(int, input().split())
    ch,cw = map(int, input().split())
    dh,dw = map(int, input().split())
    s = ["#"*(W+4)]
    s.append("#"*(W+4))
    for i in range(H):
        s.append("##"+input()+"##")
    s.append("#"*(W+4))
    s.append("#"*(W+4))
    
    ans = [[-1]*(W+4) for _ in range(H+4)]
    for i in range(H+4):
        for j in range(W+4):
            if s[i][j] == "#":
                ans[i][j] = -2
    ch += 1; cw += 1
    dh += 1; dw += 1
    ans[ch][cw] = 0
    
    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,0],[-1,1],[-1,2],\
        [0,-2],[0,-1],[0,0],[0,1],[0,2],\
        [1,-2],[1,-1],[1,0],[1,1],[1,2],\
        [2,-2],[2,-1],[2,0],[2,1],[2,2]
        ]
    
    mylist = deque([[ch,cw]])
    mylist2 = deque([])
    while len(mylist) > 0:
        x,y = mylist.popleft()
        mylist2.append([x,y])
        for p,q in move:
            v1,v2 = x+p,y+q
            if ans[v1][v2] == -1:
                mylist.append([v1,v2])
                ans[v1][v2] = ans[x][y]
        if len(mylist) == 0:
            while len(mylist2) > 0:
                x2,y2 = mylist2.popleft()
                for v1,v2 in magic:
                    i,j = x2+v1,y2+v2
                    if ans[i][j] == -1:
                        ans[i][j] = ans[x2][y2]+1
                        mylist.append([i,j])
    print(ans[dh][dw])
 
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

H,W=map(int,input().split())
si,sj=[int(x)-1 for x in input().split()]
ti,tj=[int(x)-1 for x in input().split()]
A=list(sys.stdin)

dirs=[-2,-1,0,1,2]
dist=[[10**6]*W for _ in range(H)]
dist[si][sj]=0
dq=deque()
dq.append((0,si,sj))
ok=False
while dq:
    k,i,j=dq.popleft()
    if k>dist[i][j]:
        continue
    if i==ti and j==tj:
        ok=True
        break
    for di in dirs:
        for dj in dirs:
            if di==dj==0:
                continue
            ni,nj=i+di,j+dj
            if not (0<=ni<H and 0<=nj<W):
                continue
            if A[ni][nj]=='#':
                continue
            if abs(di)+abs(dj)==1:
                append=dq.appendleft
                nk=k
            else:
                append=dq.append
                nk=k+1
            if k>=dist[ni][nj]:
                continue
            dist[ni][nj]=nk
            append((nk,ni,nj))
      
if ok:
    ans=dist[ti][tj]
else:
    ans=-1

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

H,W=map(int,input().split())
si,sj=[int(x)-1 for x in input().split()]
ti,tj=[int(x)-1 for x in input().split()]
A=list(sys.stdin)

dirs=[-2,-1,0,1,2]
dist=[[float('inf')]*W for _ in range(H)]
dist[si][sj]=0
dq=deque()
dq.append((0,si,sj))
ok=False
while dq:
    k,i,j=dq.popleft()
    if k>dist[i][j]:
        continue
    if i==ti and j==tj:
        ok=True
        break
    for di in dirs:
        for dj in dirs:
            if di==dj==0:
                continue
            ni,nj=i+di,j+dj
            if not (0<=ni<H and 0<=nj<W):
                continue
            if A[ni][nj]=='#':
                continue
            if abs(di)+abs(dj)==1:
                append=dq.appendleft
                nk=k
            else:
                append=dq.append
                nk=k+1
            if k>=dist[ni][nj]:
                continue
            dist[ni][nj]=nk
            append((nk,ni,nj))
      
if ok:
    ans=dist[ti][tj]
else:
    ans=-1

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

H,W=map(int,input().split())
si,sj=[int(x)-1 for x in input().split()]
ti,tj=[int(x)-1 for x in input().split()]
A=list(sys.stdin)

dirs=[-2,-1,0,1,2]
dist=[[float('inf')]*W for _ in range(H)]
dist[si][sj]=0
dq=deque()
dq.append((0,si,sj))
ok=False
while dq:
    k,i,j=dq.popleft()
    if i==ti and j==tj:
        ok=True
        break
    if k>dist[i][j]:
        continue
    for di in dirs:
        for dj in dirs:
            if di==dj==0:
                continue
            ni,nj=i+di,j+dj
            if not (0<=ni<H and 0<=nj<W):
                continue
            if A[ni][nj]=='#':
                continue
            if abs(di)+abs(dj)==1:
                append=dq.appendleft
                nk=k
            else:
                append=dq.append
                nk=k+1
            if k>=dist[ni][nj]:
                continue
            dist[ni][nj]=nk
            append((nk,ni,nj))
      
if ok:
    ans=dist[ti][tj]
else:
    ans=-1

print(ans)

Submission status: Accepted

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


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
import itertools as it
from collections import deque

def main(H, W, Ch, Cw, Dh, Dw, S):

    # visited[H][W]
    visited =  [[False for _ in range(W)] for __ in range(H)]

    # pick root 
    root = (Ch, Cw)
    
    # flag
    empty_while = True
    count = 0

    """DFS"""
    def DFS(node, block=set([])):
        def pick_next(node):
            h,w = node
            assert S[h][w]
            for next_h, next_w in [
                (h+1, w), # down
                (h, w+1), # right
                (h, w-1), # left
                (h-1, w)  # up
            ]:
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        # mark root as traversed
        visited[node[0]][node[1]] = True
        block.add(node)

        # if there is a node to go to 
        while pick_next(node):
            next_node = pick_next(node)
            if node:
                # mark node as traversed
                h, w = next_node
                visited[h][w] = True
                block.add(next_node)

                # go to next node
                DFS(next_node, block)
        
        return frozenset(block)

    """BFS"""
    def BFS(node):
        def pick_next(node):
            h,w = node
            r = range(-2, 3)
            for h_offset, w_offset in it.product(r,r):
                next_h = h + h_offset
                next_w = w + w_offset
                try:
                    if next_w < 0 or next_h < 0:
                        raise IndexError
                    if not visited[next_h][next_w]:
                        if S[next_h][next_w]:
                            return next_h, next_w
                except IndexError:
                    pass
            return False

        queue = deque([])
        levels = {}

        start = DFS(node)
        if visited[Dh][Dw]: 
            return 0

        queue.append(start)  
        levels[start] = 0

        while queue:
            block = queue.popleft()
            
            if visited[Dh][Dw]:
                    return levels[next_block]

            for node in block:

                while pick_next(node):
                    next_node = pick_next(node)

                    # add node to queue
                    next_block = DFS(next_node, block=set([]))
                    queue.append(next_block)
                    levels[next_block] = levels[block] + 1


        return -1 

    node = root
    count = BFS(node)    
        
    print(count)
    pass

if __name__ == '__main__':
    H, W = list(map(int, input().split()))
    Ch, Cw = list(map(int, input().split()))
    Dh, Dw = list(map(int, input().split()))
    S = [[False for _ in range(W)] for __ in range(H)]

    for h in range(H):
        S_row = input()
        for w, s in enumerate(S_row):
            if s=='.':
                S[h][w] = True
            else:
                S[h][w] = False

    Ch -= 1
    Cw -= 1
    Dh -= 1
    Dw -= 1

    main(H, W, Ch, Cw, Dh, Dw, S)