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: Time Limit Exceeded

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)
# import numpy as np
# 答えの提出の時にi+1とj+1は忘れないように
h, w = map(int, input().split())
maze = [[-1 for i in range(w)] for j in range(h)]
ch, cw = map(int, input().split())
ch, cw = ch-1, cw-1
dh, dw = map(int, input().split())
dh, dw = dh-1, dw-1


ans = 0
for i in range(h):
    maze[i] = input()

INF = h*w
distance = [[INF for i in range(w)] for j in range(h)]

queue0 = deque()
queue0.append((ch,cw))
distance[ch][cw] = 0

queue1 = deque()

while queue0 or queue1:

    if queue0:
        y, x = queue0.popleft()
    elif queue1:
        y, x = queue1.popleft()

    for dy in range(-2, 3):
        for dx in range(-2, 3):
            ny, nx = y+dy, x+dx
            if dy == dx == 0: continue
            elif abs(dy) + abs(dx) == 1:
                if 0 <= nx < w and 0 <= ny < h:
                    if maze[ny][nx] != '#' and distance[ny][nx] > distance[y][x]:
                            queue0.append((ny, nx))
                            distance[ny][nx] = distance[y][x]
            else:
                if 0 <= nx < w and 0 <= ny < h:
                    if maze[ny][nx] != '#' and distance[ny][nx] > distance[y][x]+1:
                            queue1.append((ny, nx))
                            distance[ny][nx] = distance[y][x]+1


ans = distance[dh][dw]
if ans == INF:
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def warp(p,h,w):
    ls = []
    for i in range(-2,3):
        for j in range(-2,3):
            ls.append([p[0]+i,p[1]+j])
    ret = []
    for i in range(len(ls)):
        if -1<ls[i][0]<h and -1 < ls[i][1] < w:
            ret.append(ls[i])
    return ret

def main():
    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(input())
    dis = [[-1 for i in range(w)] for i in range(h)]
    que = [[ch-1,cw-1]]
    dis[ch-1][cw-1] = 0
    g = 0
    while len(que)>0:
        nxt = []
        while len(que)>0:
            q = que.pop(0)
            if s[q[0]][q[1]] == '#':
                continue
            nxt += warp(q,h,w)
            for [mv1,mv2] in [[0,1],[0,-1],[1,0],[-1,0]]:
                if -1 < q[0]+mv1 < h and -1 < q[1]+mv2 < w:
                    if dis[q[0]+mv1][q[1]+mv2] == -1:
                        if s[q[0]+mv1][q[1]+mv2] == '.':
                            dis[q[0]+mv1][q[1]+mv2] = g
                            que.append([q[0]+mv1, q[1]+mv2])
        g += 1
        for i in range(len(nxt)):
            x,y = nxt[i][0],nxt[i][1]
            if dis[x][y] == -1:
                if s[x][y] == '.':
                    dis[x][y] = g
                    que.append([x,y])
    print(dis[dh-1][dw-1])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
h, w = list(map(int, input().split()))
si, sj = list(map(lambda x: int(x)-1, input().split()))
ti, tj = list(map(lambda x: int(x)-1, input().split()))
s = [None] * h
for i in range(h):
    s[i] = input()

# 探索時に移動する方向
di = [-1, 0, 1, 0]
dj = [0, -1, 0, 1]

# 距離情報を一番遠い値で初期化
import numpy as np
INF = int(1e9)
dist = np.full((h, w), INF)

from collections import deque
q = deque()

# 開始位置
dist[si][sj] = 0
q.append((si,sj))

while (len(q)>0):
    (i, j) = q[0]
    d = dist[i][j]
    q.popleft()
    # 移動Aによるコスト
    for v in range(len(di)):
        ni, nj = i+di[v], j+dj[v]
        if (ni<0 or ni>=h or nj<0 or nj>=w):
            continue # マップの境界
        if (s[ni][nj] == '#'):
            continue # 壁
        if (dist[ni][nj]<=d):
            continue # 探索済みコスト以上
        dist[ni][nj] = d
        q.append((ni, nj))
    # 移動Bによるコスト
    for ei in range(-2, 3):
        for ej in range(-2, 3):
            ni, nj = i+ei, j+ej
            if (ni<0 or ni>=h or nj<0 or nj>=w):
                continue # マップの境界
            if (s[ni][nj] == '#'):
                continue # 壁
            if (dist[ni][nj]<=d):
                continue # 探索済みコスト以上
            dist[ni][nj] = d+1
            q.append((ni, nj))

ans = dist[ti][tj]
if ans == INF:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
INF = float("inf")

h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
ch, cw = ch-1, cw-1
dh, dw = dh-1, dw-1
S = [input() for _ in range(h)]

dist = [[INF] * w for _ in range(h)]
dist[ch][cw] = 0
q = deque([(cw, ch)])

while q:
    x, y = q.popleft()
    for _x in range(-2, 3):
        for _y in range(-2, 3):
            if _x == _y == 0:
                continue
            next_x, next_y = x + _x, y + _y
            if not 0 <= next_x < w:
                continue
            if not 0 <= next_y < h:
                continue
            if S[next_y][next_x] == "#":
                continue
            if abs(_x) + abs(_y) <= 1:
                if dist[next_y][next_x] <= dist[y][x]:
                    continue
                q.appendleft((next_x, next_y))
                dist[next_y][next_x] = dist[y][x]
            else:
                if dist[next_y][next_x] <= dist[y][x] + 1:
                    continue
                q.append((next_x, next_y))
                dist[next_y][next_x] = dist[y][x] + 1

if dist[dh][dw] != INF:
    print(dist[dh][dw])
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from collections import deque

    h, w = map(int, input().split())
    c_h, c_w = map(int, input().split())
    c_h -= 1
    c_w -= 1
    d_h, d_w = map(int, input().split())
    d_h -= 1
    d_w -= 1
    dist = [[10**18 for i in range(w)] for i in range(h)]
    dist[c_h][c_w] = 0

    C = []
    for _ in range(h):
        C.append(list(input()))
    D = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    queue = deque([(c_h, c_w)])

    while queue:
        (x, y) = queue.popleft()
        d = dist[x][y]

        for (dx, dy) in D:
            new_x, new_y = x + dx, y + dy
            if -1 < new_x < h and -1 < new_y < w:
                if C[new_x][new_y] == '.' and dist[new_x][new_y] > d:
                    dist[new_x][new_y] = d
                    queue.appendleft((new_x, new_y))

        for dx in range(-2, 3):
            for dy in range(-2, 3):
                if -1 < x + dx < h and -1 < y + dy < w and (dx != 0 or dy != 0):
                    if C[x + dx][y + dy] == '.' and dist[x + dx][y + dy] > d:
                        dist[x + dx][y + dy] = d + 1
                        queue.append((x + dx, y + dy))

    ans = dist[d_h][d_w]
    if ans == 10**18:
        print(-1)
    else:
        print(ans)

resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    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 = [[-1 for _ in range(W)] for _ in range(H)]

    q = deque([])
    q.appendleft((0, Ch - 1, Cw - 1))

    while len(q):
        worp_count, x, y = q.popleft()

        if d[x][y] != -1:
            continue
        d[x][y] = worp_count

        for i, j in ((a, b) for a in range(-2, 3) for b in range(-2, 3)):
            nx = x + i
            ny = y + j
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                if i == 0 and j == 0:
                    continue
                elif abs(i) + abs(j) == 1:
                    q.appendleft((worp_count, nx, ny))
                else:
                    q.append((worp_count + 1, nx, ny))

    print(d[Dh - 1][Dw - 1])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


if __name__ == '__main__':

    H, W = map(int, input().split())
    s_h, s_w = map(int, input().split())
    e_h, e_w = map(int, input().split())

    s_h -= 1
    s_w -= 1
    e_h -= 1
    e_w -= 1

    M = []

    for i in range(H):
        s = input()
        M.append(s)

    found = False

    dq = deque()
    dist = [[True for _ in range(W)] for _ in range(H)]

    for i in range(H):
        for j in range(W):
            dist[i][j] = 1e7

    dist[s_h][s_w] = 0

    dq.append((s_h, s_w))

    while dq:
        h, w = dq.pop()
        # print(h, w)
        if h == e_h and w == e_w:
            found = True
            break
        for dx in range(-2, 3, 1):
            for dy in range(-2, 3, 1):
                nh = h + dx
                nw = w + dy
                if dx == 0 and dy == 0:
                    continue
                if nh >= H or nh < 0 or nw >= W or nw < 0:
                    continue
                d = 1
                if M[nh][nw] == '#':
                    continue
                if (abs(dx) == 1 and abs(dy) == 0) or (abs(dy) == 1 and abs(dx) == 0):
                    d = 0
                if dist[nh][nw] > dist[h][w] + d:
                    dist[nh][nw] = dist[h][w] + d
                    if d == 0:
                        dq.append((nh, nw))
                    else:
                        dq.appendleft((nh, nw))
    if not found:
        dist[e_h][e_w] = -1
    print(dist[e_h][e_w])
    # for dx in range(-2, 3, 1):
    #         for dy in range(-2, 3, 1):
    #             print(dx, dy)

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from collections import deque


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    d = [[-1 for i in range(W)] for j in range(H)]
    q = deque([])
    q.appendleft((0, Ch - 1, Cw - 1))
    resolve(q, d, S, (Dh - 1, Dw - 1), H, W)
    print(d[Dh - 1][Dw - 1])


def resolve(q, d, S, D, H, W):
    while len(q):
        worp_count, x, y = q.popleft()

        if d[x][y] != -1:
            continue
        d[x][y] = worp_count

        for i, j in ((a, b) for a in range(-2, 3) for b in range(-2, 3)):
            nx = x + i
            ny = y + j
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == '.':
                if abs(i) + abs(j) == 1:
                    q.appendleft((worp_count, nx, ny))
                elif abs(i) + abs(j) >= 2:
                    q.append((worp_count + 1, nx, ny))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    from collections import deque

    h, w = map(int, input().split())
    c_h, c_w = map(int, input().split())
    c_h -= 1
    c_w -= 1
    d_h, d_w = map(int, input().split())
    d_h -= 1
    d_w -= 1
    dist = [[10**18 for i in range(w)] for i in range(h)]
    dist[c_h][c_w] = 0

    C = []
    for _ in range(h):
        C.append(list(input()))
    D = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    queue = deque([(c_h, c_w)])

    while queue:
        (x, y) = queue.popleft()
        d = dist[x][y]

        for (dx, dy) in D:
            new_x, new_y = x + dx, y + dy
            if -1 < new_x < h and -1 < new_y < w:
                if C[new_x][new_y] == '.' and dist[new_x][new_y] > d:
                    dist[new_x][new_y] = d
                    queue.appendleft((new_x, new_y))

        for dx in range(-2, 3):
            for dy in range(-2, 3):
                if -1 < x + dx < h and -1 < y + dy < w:
                    if C[x + dx][y + dy] == '.' and dist[x + dx][y + dy] > d:
                        dist[x + dx][y + dy] = d + 1
                        queue.append((x + dx, y + dy))

    ans = dist[d_h][d_w]
    if ans == 10**18:
        print(-1)
    else:
        print(ans)

resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q = deque([])
    q.appendleft((0, Ch - 1, Cw - 1))
    answer = resolve(q, S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(q, S, D, H, W):
    while len(q):
        worp_count, x, y = q.popleft()
        S[x][y] = '/'

        if (x, y) == D:
            return worp_count

        for i, j in ((a, b) for a in range(-2, 3) for b in range(-2, 3)):
            if 0 <= x + i < H and 0 <= y + j < W and S[x + i][y + j] == '.':
                if abs(i) + abs(j) == 1:
                    q.appendleft((worp_count, x + i, y + j))
                else:
                    q.append((worp_count + 1, x + i, y + j))

    return -1


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from collections import deque


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q = deque([])
    q.appendleft((0, Ch - 1, Cw - 1))
    answer = resolve(q, S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(q, S, D, H, W):
    while len(q):
        worp_count, x, y = q.popleft()
        S[x][y] = '/'

        if (x, y) == D:
            return worp_count

        for i, j in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
            if 0 <= i < H and 0 <= j < W and S[i][j] in ('.', '1'):
                q.appendleft((worp_count, i, j))
                S[i][j] = '0'

        for i, j in ((x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)):
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.append((worp_count + 1, i, j))
                S[i][j] = '1'

    return -1


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
def main(wall, Sx, Sy, Tx, Ty):
    INF = 1 << 30
    H, W = wall.shape
    S = Sx * W + Sy
    T = Tx * W + Ty
    dist = np.full(H * W, INF, np.int64)
    deq = np.empty(H * W + 100, np.int64)
    dist[S] = 0
    deq[0], l, r = S, 0, 1
    while l < r:
        v, l = deq[l], l + 1
        vx, vy = divmod(v, W)
        # そのままあるく
        for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            wx, wy = vx + dx, vy + dy
            if not (0 <= wx < H):
                continue
            if not (0 <= wy < W):
                continue
            if wall[wx, wy]:
                continue
            w = wx * W + wy
            if dist[w] <= dist[v]:
                continue
            dist[w] = dist[v]
            deq[l - 1], l = w, l - 1
        # ワープする
        for dx in range(-2, 3):
            for dy in range(-2, 3):
                wx, wy = vx + dx, vy + dy
                if not (0 <= wx < H):
                    continue
                if not (0 <= wy < W):
                    continue
                if wall[wx, wy]:
                    continue
                w = wx * W + wy
                if dist[w] <= dist[v] + 1:
                    continue
                dist[w] = dist[v] + 1
                deq[r], r = w, r + 1
    ans = dist[T]
    if ans == INF:
        ans = -1
    return ans


H, W = map(int, readline().split())
Sx, Sy = map(lambda x: int(x) - 1, readline().split())
Tx, Ty = map(lambda x: int(x) - 1, readline().split())
wall = np.frombuffer(read(), 'S1').reshape(H, -1)[:, :W] == b'#'

print(main(wall, Sx, Sy, Tx, Ty))

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from queue import PriorityQueue


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q = PriorityQueue(H * W)
    q.put((0, (Ch - 1, Cw - 1)))

    answer = resolve(q, S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(q, S, D, H, W):
    while not q.empty():
        worp_count, (x, y) = q.get()
        S[x][y] = '/'

        if (x, y) == D:
            return worp_count

        for i, j in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
            if 0 <= i < H and 0 <= j < W and S[i][j] in ('.', '1'):
                q.put((worp_count, (i, j)))
                S[i][j] = '0'

        for i, j in ((x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)):
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count + 1, (i, j)))
                S[i][j] = '1'

    return -1


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from queue import PriorityQueue


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q = PriorityQueue(H * W)
    q.put((0, (Ch - 1, Cw - 1)))

    answer = resolve(q, S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(q, S, D, H, W):
    while not q.empty():
        worp_count, (x, y) = q.get()
        S[x][y] = '/'

        if (x, y) == D:
            return worp_count

        for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] in ('.', '1'):
                q.put((worp_count, (i, j)))
                S[i][j] = '0'

        for i, j in [(x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count + 1, (i, j)))
                S[i][j] = '1'

    return -1


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from queue import PriorityQueue

q = PriorityQueue()


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q.put((0, (Ch - 1, Cw - 1)))

    answer = resolve(S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(S, D, H, W):
    while not q.empty():
        worp_count, (x, y) = q.get()
        S[x][y] = '/'

        if (x, y) == D:
            return worp_count

        for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] in ('.', '1'):
                q.put((worp_count, (i, j)))
                S[i][j] = '0'

        for i, j in [(x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)]:
            if (i, j) in ((x, y), (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
                continue
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count + 1, (i, j)))
                S[i][j] = '1'

    return -1


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from queue import PriorityQueue

q = PriorityQueue()


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q.put((0, (Ch - 1, Cw - 1)))

    answer = resolve(S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(S, D, H, W):
    while not q.empty():
        worp_count, (x, y) = q.get()
        S[x][y] = '/'

        if (x, y) == D:
            return worp_count

        for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] in ('.', '1'):
                q.put((worp_count, (i, j)))
                S[i][j] = '0'

        for i, j in [(x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count + 1, (i, j)))
                S[i][j] = '1'

    return -1


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
infty = 10 ** 12

def BFS(dist):
    start = (C_H-1)*W + C_W-1
    queue = deque()
    queue.append((start, 0))
    searched = [False for k in range(len(dist))] #少なくとも1回探索されたか否か
    determined = [False for k in range(len(dist))] #最短距離が決まったか否か
    L = 1
    searched[start] = True
    while queue:
        add_v = 0
        while L > 0:
            v = queue.popleft()
            if not determined[v[0]]:
                determined[v[0]] = True
                dist[v[0]] = v[1]
            L -= 1
            row = v[0]//W
            col = v[0]%W
            for k in range(5):
                for l in range(5):
                    if (k, l) == (2, 2):
                        continue
                    else:
                        if S_extended[row + k][col + l] == "." and not determined[(row+k-2)*W + col+l-2]:
                            searched[(row+k-2)*W + col+l-2] = True
                            add_v += 1
                            if (k, l) in [(1, 2), (2, 1), (2, 3), (3, 2)]:
                                queue.appendleft(((row+k-2)*W + col+l-2, v[1]))
                            else:
                                queue.append(((row+k-2)*W + col+l-2, v[1]+1))
        L = add_v

H, W = map(int, input().split())
C_H, C_W = map(int, input().split())
D_H, D_W = map(int, input().split())

graph = [[] for i in range(H*W)]
S = []
for i in range(H):
    S.append(input())

s = ""
for j in range (W+4):
    s += "#"
S_extended = [s, s]
for i in range(H):
    S_extended.append("##" + S[i] + "##")
S_extended.append(s)
S_extended.append(s)

dist = [infty for i in range(H*W)]
BFS(dist)
if dist[(D_H-1)*W + D_W-1] == infty:
    print("-1")
else:
    print(dist[(D_H-1)*W + D_W-1])

Submission status: Time Limit Exceeded

Solution code:
import copy
(H,W) = map(int,input().split())
(ch,cw) = map(int,input().split())
(dh,dw) = map(int,input().split())
l = []
for i in range(H):
    k=input()
    l.append([k[j] for j in range(W)])
t = copy.deepcopy(l)
s = [[-1 for i in range(W)] for j in range(H)]
ans = 0
rn = 0
u = []
cn = -1
dn = -1
k = []

def black(h,w):
    global k

    if (ch-1,cw-1) == (h,w):
        global cn
        cn = rn
    if (dh-1,dw-1) == (h,w):
        global dn
        dn = rn
    if s[h][w] != -1:
        if [s[h][w],rn] not in u:
            u.append([s[h][w],rn])

    t[h][w]="#"
    k.append([h,w])
    if w<(W-1):
        if t[h][w+1]==".":
            black(h,w+1)
    if h<(H-1):
        if t[h+1][w]==".":
            black(h+1,w)
    if w>0:
        if t[h][w-1]==".":
            black(h,w-1)
    if h>0:
        if t[h-1][w]==".":
            black(h-1,w)

def wrap(k):
    for i in range(len(k)):
        for pi in range(-2,3):
            for pj in range(-2,3):
                if 0<=(k[i][0]+pi) and ((k[i][0]+pi)<H and (0<=(k[i][1]+pj) and (k[i][1]+pj)<W)):
                    if t[k[i][0]+pi][k[i][1]+pj] == ".":
                        s[k[i][0]+pi][k[i][1]+pj] = rn

for i in range(H):
    for j in range(W):
        if t[i][j] == ".":
            black(i,j)
            wrap(k)
            k = []
            rn += 1
            l = copy.deepcopy(t)

mat = [cn]
mit = []
v = [[0 for i in range(rn)] for j in range(rn)]
for i in range(len(u)):
    v[u[i][0]][u[i][1]] = 1

count = len(u)
if dn == cn:
    print(0)
while dn not in mat:
    mit = []
    for x in mat:
        for i in range(rn):
            if v[min(x,i)][max(x,i)] == 1:
                mit.append(i)
                v[min(x,i)][max(x,i)] = 0
                count -= 1
        mat.remove(x)
        mat = copy.deepcopy(mit)
    ans += 1
    if dn in mat:
        print(ans)
    elif count == 0:
        print(-1)
        break

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from queue import PriorityQueue

q = PriorityQueue()


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q.put((0, (Ch - 1, Cw - 1)))

    answer = resolve(S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(S, D, H, W):
    while not q.empty():
        worp_count, (x, y) = q.get()
        S[x][y] = '/'

        if (x, y) == D:
            return worp_count

        for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count, (i, j)))

        for i, j in [(x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count + 1, (i, j)))

    return -1


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from queue import Queue

q = Queue()
cell_list = list()


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q.put((0, Ch - 1, Cw - 1))
    S[Ch - 1][Cw - 1] = '/'

    answer = resolve(S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(S, D, H, W):
    while not q.empty():
        worp_count, x, y = q.get()
        cell_list.append((x, y))

        if (x, y) == D:
            return worp_count

        for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count, i, j))
                S[i][j] = '/'

    for x, y in cell_list:
        for i, j in [(x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count + 1, i, j))
                S[i][j] = '/'

    if q.empty():
        return -1

    return resolve(S, D, H, W)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# 正解ではない

from queue import Queue

q = Queue()
cell_list = list()


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q.put((0, Ch - 1, Cw - 1))
    S[Ch - 1][Cw - 1] = '1'

    answer = resolve(S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(S, D, H, W):
    if q.empty():
        return -1

    while not q.empty():
        worp_count, x, y = q.get()
        S[x][y] = '2'
        cell_list.append((x, y))

        if (x, y) == D:
            return worp_count

        for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count, i, j))

    for x, y in cell_list:
        for i, j in [(x + a, y + b) for a in range(-2, 3) for b in range(-2, 3)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count + 1, i, j))
                S[i][j] = '1'

    return resolve(S, D, H, W)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue

q = Queue()
cell_list = list()


def main():
    H, W = map(int, input().split())
    Ch, Cw = map(int, input().split())
    Dh, Dw = map(int, input().split())
    S = [list(input()) for i in range(H)]
    q.put((0, Ch - 1, Cw - 1))
    S[Ch - 1][Cw - 1] = '1'

    answer = resolve(S, (Dh - 1, Dw - 1), H, W)
    print(answer)


def resolve(S, D, H, W):
    if q.empty():
        return -1

    while not q.empty():
        worp_count, x, y = q.get()
        S[x][y] = '2'
        cell_list.append((x, y))

        if (x, y) == D:
            return worp_count

        for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
            if 0 <= i < H and 0 <= j < W and S[i][j] == '.':
                q.put((worp_count, i, j))

    for x, y in cell_list:
        for i, j in [(a, b) for a in range(-2, 3) for b in range(-2, 3)]:
            if 0 <= x + i < H and 0 <= y + j < W and S[x + i][y + j] == '.':
                q.put((worp_count + 1, x + i, y + j))
                S[x + i][y + j] = '1'

    return resolve(S, D, H, W)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
# from queue import PriorityQueue

H = 0
W = 0

def within_interval(h, w):
    global H
    global W
    if 0 <= h < H and 0 <= w < W:
        return True
    return False


def find_distance(start_h, start_w, end_h, end_w, M):

    #possible moves of type A
    d_a = [(0, 1), (1, 0), (-1, 0), (0, -1)]
    #possible moves of type B
    d_b = [(-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)]

    q1 = deque()
    q1.append((0, start_h, start_w))

    # q = PriorityQueue()
    # q.put((0, start_h, start_w))

    while q1:#not(q1.empty()):

        d, h, w = q1.pop()
        M[h][w] = True
        # print(h, w)
        #if reached the node we wanted we move
        if h == end_h and w == end_w:
            return d

        for shift in d_a:
            #check if we reached the end
            dh = h + shift[0]
            dw = w + shift[1]
            if within_interval(dh, dw) and not(M[dh][dw]):
                q1.append((d, dh, dw))
                # q.put((d, move[0], move[1]))
        for shift in d_b:
            #check if we reached the end
            dh = h + shift[0]
            dw = w + shift[1]
            if within_interval(dh, dw) and not(M[dh][dw]):
                q1.appendleft((d + 1, dh, dw))
                # q.put((d + 1, move[0], move[1]))
    return -1


if __name__ == '__main__':

    H, W = map(int, input().split())
    c_h, c_w = map(int, input().split())
    d_h, d_w = map(int, input().split())

    # M_ = dict()
    M = [[True for _ in range(W)] for _ in range(H)]

    for i in range(H):
        s = input()
        for j in range(len(s)):
            if s[j] == '.':
                # M_[(i,j)] = False
                M[i][j] = False

    # print(M)
    res = find_distance(c_h - 1, c_w - 1, d_h - 1, d_w - 1, M)
    print(res)

# 4 4
# 1 1
# 4 4
# ..#.
# ..#.
# .#..
# .#..