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

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


    while dq1:

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

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


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

main()

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
si, sj = map(int, input().split())
gi, gj = map(int, input().split())
si, sj, gi, gj = si-1+2, sj-1+2, gi-1+2, gj-1+2
X = [[1] * (W + 4)] * 2 + [[1] * 2 + [1 if a == "#" else 0for a in input()] + [1] * 2 for _ in range(H)] + [[1] * (W + 4)] * 2
H += 4
W += 4

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

def BFS():
    Q = deque([(si, sj)])
    D = [-1] * (H * W)
    D[si*W + sj] = 0
    while Q:
        i, j = Q.popleft()
        x = i * W + j
        for di, dj in Y:
            ni, nj = i+di, j+dj
            y = ni * W + nj
            if X[ni][nj] == 0:
                if D[y] == -1 or D[y] > D[x]:
                    D[y] = D[x]
                    Q.appendleft((ni, nj))
        for di, dj in Z:
            ni, nj = i+di, j+dj
            y = ni * W + nj
            if X[ni][nj] == 0:
                if D[y] == -1:
                    D[y] = D[x] + 1
                    Q.append((ni, nj))
    return D[gi * W + gj]

print(BFS())

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 = []
for _ in range(H):
    S.append(list(input()))

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

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

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

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

Submission status: Accepted

Solution code:
from collections import deque
from itertools import product

INF = 10**18

H, W = map(int, input().split())
C = list(map(int, input().split()))
D = list(map(int, input().split()))
S = [input() for _ in range(H)]

# H, W = 10**3, 10**3
# C = [1, 1]
# D = [H, W]
# S = [["."]*W]*H
# S[24] = ["#"]*W
# for y in range(H):
#     S[y][234] = "#"
#     S[y][236] = "#"
# print("p")

# H, W = 5, 5
# C = [1, 1]
# D = [3, 3]
# S = [
#     ".....",
#     "####.",
#     "...#.",
#     ".###.",
#     ".....",
# ]

s_pos = sx, sy = C[1]-1, C[0]-1
g_pos = gx, gy = D[1]-1, D[0]-1

# dist init
dist = [[INF for _ in range(W)] for _ in range(H)]
dist[sy][sx] = 0
# visited init
visited = [[0 for _ in range(W)] for _ in range(H)]
q = deque([s_pos])

while q:
    t_pos = tx, ty = q.popleft()
    t_dist = dist[ty][tx]

    if visited[ty][tx]:
        continue
    # visited edit
    visited[ty][tx] = 1

    for dx, dy in product(range(-2, 3), repeat=2):
        if dx == dy == 0:
            continue
        pos = x, y = tx+dx, ty+dy
        if not (0 <= x < W and 0 <= y < H):
            continue
        if S[y][x] == "#":
            continue
        cost = int(abs(dx)+abs(dy) > 1)
        if dist[y][x] <= t_dist + cost:
            continue
        # dist edit
        dist[y][x] = t_dist + cost
        if cost == 0:
            q.appendleft(pos)
        else:
            q.append(pos)

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

Submission status: Accepted

Solution code:
from collections import deque

H, W = [int(x) for x in input().split()]
c_h, c_w = [int(x) - 1 for x in input().split()]  # Convert to 0-origin
d_h, d_w = [int(x) - 1 for x in input().split()]  # Convert to 0-origin
s = [['.' for w in range(W)] for h in range(H)]
for h in range(H):
    s[h] = input()

def in_the_map(x):
    if x[0] < 0 or H <= x[0] or x[1] < 0 or W <= x[1]:
        return False
    return True

costs = [[-1 for w in range(W)] for h in range(H)]
queue = deque()
queue.append((c_h, c_w, 0))
while len(queue) > 0:
    q = queue.popleft()
    h = q[0]
    w = q[1]
    c = q[2]
    if costs[h][w] > -1:
        continue
    # print(f'{h}, {w}: {c}')
    costs[h][w] = c
    
    # Explore neighbours where can be visited with the same cost as this point
    neighbours = ((h, w - 1), (h, w + 1), (h - 1, w), (h + 1, w))
    for n in neighbours:
        if not in_the_map(n) or costs[n[0]][n[1]] > -1:  # 01-BFS assures that the cost we have recorded is the smallest
            continue
        if s[n[0]][n[1]] == '.':  # not wall
            queue.appendleft((n[0], n[1], c))  # This operation assures that the point with the lowest cost (+0) is popped earlier

    for dh in range(-2, 3):
        for dw in range(-2, 3):
            hh = h + dh 
            ww = w + dw
            if not in_the_map((hh, ww)) or costs[hh][ww] > -1:
                continue
            if s[hh][ww] == '.':
                queue.append((hh, ww, c+1))

print(costs[d_h][d_w])

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
S = [input() for _ in range(H)]
global_visited = set()

count = [[float("inf")] * W for _ in range(H)]

start = (ch - 1, cw -1)

def judge(start):
    if start in global_visited:
        return False
    if start[0] < 0 or H <= start[0]:
        return False
    if start[1] < 0 or W <= start[1]:
        return False
    if S[start[0]][start[1]] == '#':
        return False
    return True

que = [start]
now_count = 0
while que:
    local_visited = []
    while que:
        start = que.pop()
        global_visited.add(start)
        local_visited.append(start)
        count[start[0]][start[1]] = now_count
        next_list = [
            (start[0], start[1] + 1),
            (start[0], start[1] - 1),
            (start[0] + 1, start[1]),
            (start[0] - 1, start[1]),
        ]
        for next in next_list:
            if judge(next):
                que.append(next)

    now_count += 1

    while local_visited:
        start = local_visited.pop()
        next_list = [
            (start[0] + 2, start[1] + 2),
            (start[0] + 2, start[1] + 1),
            (start[0] + 2, start[1] + 0),
            (start[0] + 2, start[1] - 1),
            (start[0] + 2, start[1] - 2),
            (start[0] + 1, start[1] + 2),
            (start[0] + 1, start[1] + 1),
            (start[0] + 1, start[1] - 1),
            (start[0] + 1, start[1] - 2),
            (start[0] + 0, start[1] + 2),
            (start[0] + 0, start[1] - 2),
            (start[0] - 1, start[1] + 2),
            (start[0] - 1, start[1] + 1),
            (start[0] - 1, start[1] - 1),
            (start[0] - 1, start[1] - 2),
            (start[0] - 2, start[1] + 2),
            (start[0] - 2, start[1] + 1),
            (start[0] - 2, start[1] + 0),
            (start[0] - 2, start[1] - 1),
            (start[0] - 2, start[1] - 2),
        ]
        for next in next_list:
            if judge(next):
                count[next[0]][next[1]] = now_count
                global_visited.add(next)
                que.append(next)

if count[dh-1][dw-1] == float("inf"):
    print(-1)
else:
    print(count[dh-1][dw-1])

Submission status: Accepted

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

import heapq

INF = 10 ** 10

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

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


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

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

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

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

dist = dijkstra(N, es, ch*W+cw)
if dist[gh*W+gw] == INF:
    print(-1)
else:
    print(dist[gh*W+gw])

Submission status: Accepted

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


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

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

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

    def _flatten_coordinate(self, x: int, y: int) -> int:
        return self.width * (x + 1) + y + 1

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

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

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

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

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

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


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

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

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


if __name__ == "__main__":
    main()