Problem:


Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

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

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

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

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2



Sample input:
4 4
1 1
4 4
..#.
..#.
.#..
.#..


Sample output:
1

Submission status: Wrong Answer

Solution code:
def good(x,y):
    if (x>=0 and x<h) and (y>=0 and y<w):
        return (mat[x][y] != "#")
h, w = map(int,input().split())
sh, sw = map(int,input().split())
eh, ew = map(int,input().split())
mat = []
for _ in range(h):
    s = input()
    mat.append(s)
x = [1,-1,0,0]
y = [0,0,-1,1]
dist = [[float('inf') for i in range(w)]for j in range(h)]
sh -= 1
sw -= 1
eh -= 1
ew -= 1
dist[sh][sw] = 0
queue = [(sh,sw)]
while queue:
    m = queue.pop(0)
    for d in range(4):
        nx = m[0] + x[d]
        ny = m[1] + y[d]
        if good(nx,ny):
            if dist[nx][ny] > dist[m[0]][m[1]]:
                dist[nx][ny] =  dist[m[0]][m[1]]
                queue.insert(0,(nx,ny))
    for i in range(m[0]-2,m[1]+3):
        for j in range(m[1]-2,m[1]+3):
            if good(i,j):
                if dist[i][j] > dist[m[0]][m[1]] + 1:
                    dist[i][j] = dist[m[0]][m[1]] + 1
                    queue.append((i,j))
if dist[eh][ew] == float('inf'):
    print(-1)
else:
    print(dist[eh][ew])

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())

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

grid = [list(input()) for s in range(H)]

search = [[float('inf')] * W for _ in range(H)]
visit = [[False] * W for _ in range(H)]
dq = deque([])

dq.append((Ch, Cw))
search[Ch][Cw] = 0
visit[Ch][Cw] = True

direction = [[-1, 0], [0, -1], [1, 0], [0, 1]]

while dq:
    cur_row, cur_col = dq.popleft()
    cur_step = search[cur_row][cur_col]

    dq_in = deque([])
    dq_in.append((cur_row, cur_col))

    warp_can = []
    while dq_in:
        r, c = dq_in.popleft()

        flag = False
        for dir_y, dir_x in direction:
            new_row = r + dir_x
            new_col = c + dir_y

            if new_row < 0 or new_row >= H or new_col < 0 or new_col >= W:
                continue

            if visit[new_row][new_col]:
                continue

            if grid[new_row][new_col] == '#':
                if not flag:
                    warp_can.append((r, c))
                    flag = True
            else:
                search[new_row][new_col] = cur_step
                dq_in.append((new_row, new_col))

        visit[r][c] = True

    next_island = []
    for w_row, w_col in warp_can:
        for r in range(-2, 3):
            x_row = w_row + r
            for c in range(-2, 3):
                if r == 0 and c == 0:
                    continue

                x_col = w_col + c

                if x_row < 0 or x_row >= H or x_col < 0 or x_col >= W:
                    continue

                if grid[x_row][x_col] == '#':
                    continue

                if visit[x_row][x_col]:
                    continue

                next_island.append((x_row, x_col))

    for x, y in next_island:
        search[x][y] = min(cur_step + 1, search[x][y])

        if not visit[x][y]:
            dq.append((x, y))
            visit[x][y] = True


if search[Dh][Dw] == float('inf'):
    print(-1)
else:
    print(search[Dh][Dw])

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
graphlist = []
grapht = [[-1 for i in range(w+2)] for i in range(h+2)]
meiro = [["#" for i in range(w+2)]]+[["#"]+list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]
lastnum=[0]
donelist = set()
for i in range(1, h+1):
    for j in range(1, w+1):
        if(meiro[i][j] == "."):
            if(grapht[i-1][j] != -1):
                grapht[i][j] = grapht[i-1][j]
            elif(grapht[i][j-1] != -1):
                grapht[i][j] = grapht[i][j-1]
            elif(grapht[i+1][j] != -1):
                grapht[i][j] = grapht[i+1][j]
            elif(grapht[i][j+1] != -1):
                grapht[i][j] = grapht[i][j+1]
            else:
                grapht[i][j] = lastnum
                graphlist.append(set())
                lastnum = [lastnum[0] + 1]
            if(meiro[i+1][j] == "."):
                grapht[i+1][j] = grapht[i][j]
            if(meiro[i][j+1] == "."):
                if(grapht[i][j+1] == -1):
                    grapht[i][j+1] = grapht[i][j]
                elif(grapht[i][j] != grapht[i][j+1]):
                    donelist.add(grapht[i][j+1][0])
                    graphlist[grapht[i][j][0]] = graphlist[grapht[i][j][0]] | (graphlist[grapht[i][j+1][0]] - set(grapht[i][j]))
                    for k in graphlist[grapht[i][j+1][0]]:
                        graphlist[k].add(grapht[i][j][0])
                    grapht[i][j+1][0] = grapht[i][j][0]
            for k in range(i-2, i+3):
                if(k >= h+1):
                    continue
                for l in range(j-2, j+3):
                    if(l >= w+1):
                        continue
                    if(grapht[k][l] != -1 and grapht[k][l] != grapht[i][j]):
                        graphlist[grapht[i][j][0]].add(grapht[k][l][0])
                        graphlist[grapht[k][l][0]].add(grapht[i][j][0])
start = grapht[ch][cw][0]
end = grapht[dh][dw][0]
nextlist = queue.Queue()
depthlist = [-1]*len(graphlist)
donelist.add(start)
depthlist[start] = 0
while True:
    for i in graphlist[start]:
        if(i not in donelist):
            nextlist.put(i)
            depthlist[i] = depthlist[start]+1
            donelist.add(i)
    if(nextlist.empty()):
        break
    start = nextlist.get()
#import pprint        
#pprint.pprint(grapht)
#print(graphlist)
print(depthlist[end])

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
graphlist = []
grapht = [[-1 for i in range(w+2)] for i in range(h+2)]
meiro = [["#" for i in range(w+2)]]+[["#"]+list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]
lastnum=[0]
donelist = set()
for i in range(1, h+1):
    for j in range(1, w+1):
        if(meiro[i][j] == "."):
            if(grapht[i-1][j] != -1):
                grapht[i][j] = grapht[i-1][j]
            elif(grapht[i][j-1] != -1):
                grapht[i][j] = grapht[i][j-1]
            elif(grapht[i+1][j] != -1):
                grapht[i][j] = grapht[i+1][j]
            elif(grapht[i][j+1] != -1):
                grapht[i][j] = grapht[i][j+1]
            else:
                grapht[i][j] = lastnum
                graphlist.append(set())
                lastnum = [lastnum[0] + 1]
            if(meiro[i+1][j] == "."):
                grapht[i+1][j] = grapht[i][j]
            if(meiro[i][j+1] == "."):
                if(grapht[i][j+1] == -1):
                    grapht[i][j+1] = grapht[i][j]
                else:
                    donelist.add(grapht[i][j+1][0])
                    graphlist[grapht[i][j][0]] = graphlist[grapht[i][j][0]] | (graphlist[grapht[i][j+1][0]] - set(grapht[i][j]))
                    for k in graphlist[grapht[i][j+1][0]]:
                        graphlist[k].add(grapht[i][j][0])
                    grapht[i][j+1][0] = grapht[i][j][0]
            for k in range(i-2, i+3):
                if(k >= h+1):
                    continue
                for l in range(j-2, j+3):
                    if(l >= w+1):
                        continue
                    if(grapht[k][l] != -1 and grapht[k][l] != grapht[i][j]):
                        graphlist[grapht[i][j][0]].add(grapht[k][l][0])
                        graphlist[grapht[k][l][0]].add(grapht[i][j][0])
start = grapht[ch][cw][0]
end = grapht[dh][dw][0]
nextlist = queue.Queue()
depthlist = [-1]*len(graphlist)
donelist.add(start)
depthlist[start] = 0
while True:
    for i in graphlist[start]:
        if(i not in donelist):
            nextlist.put(i)
            depthlist[i] = depthlist[start]+1
            donelist.add(i)
    if(nextlist.empty()):
        break
    start = nextlist.get()
import pprint        
pprint.pprint(grapht)
print(graphlist)
print(depthlist[end])

Submission status: Wrong Answer

Solution code:
import os
import sys

import numpy as np
from heapq import heappop, heappush


def solve(h, w, s, t, field):
    WARP = (-(w * 2 + 10), -(w * 2 + 9), -(w * 2 + 8), -(w * 2 + 7), -(w * 2 + 6),
            -(w + 6), -(w + 5), -(w + 3), -(w + 2),
            -2, 2,
            w + 2, w + 3, w + 5, w + 6,
            w * 2 + 6, w * 2 + 7, w * 2 + 8, w * 2 + 9, w * 2 + 10)
    WALK = (-(w + 4), -1, 1, w + 4)

    qc = np.zeros(1000000, dtype=np.int16)
    qv = np.zeros(1000000, dtype=np.int16)
    qv[0] = s
    l, r = 0, 1
    visited = np.zeros((h + 4) * (w + 4), np.int8)
    queued = np.zeros((h + 4) * (w + 4), np.int8)
    queued[s] = 1
    while l < r:
        cost = qc[l]
        v = qv[l]
        l += 1
        if v == t:
            return cost
        if visited[v]:
            continue
        visited[v] = 1
        for d in WALK:
            u = v + d
            if field[u] or visited[u] or queued[u]:
                continue
            queued[u] = 1
            l -= 1
            qc[l] = cost
            qv[l] = u
        for d in WARP:
            u = v + d
            if field[u] or visited[u] or queued[u]:
                continue
            qc[r] = cost + 1
            qv[r] = u
            r += 1

    return -1


if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC

    cc = CC('my_module')
    cc.export('solve', '(i8,i8,i8,i8,i1[:],)')(solve)
    cc.compile()
    exit()

if os.name == 'posix':
    # noinspection PyUnresolvedReferences
    from my_module import solve
else:
    from numba import njit

    solve = njit('(i8,i8,i8,i8,i1[:],)', cache=True)(solve)
    print('compiled', file=sys.stderr)

h, w = map(int, sys.stdin.readline().split())
ch, cw = map(int, sys.stdin.readline().split())
dh, dw = map(int, sys.stdin.readline().split())
field = np.ones((h + 4) * (w + 4), dtype=np.int8)
for i in range(h):
    line = sys.stdin.readline().strip()
    field[(i + 2) * (w + 4) + 2:(i + 2) * (w + 4) + w + 2] = list(map('.#'.index, line))
s = (ch + 1) * (w + 4) + cw + 1
t = (dh + 1) * (w + 4) + dw + 1
ans = solve(h, w, s, t, field)
print(ans)

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
graphlist = []
grapht = [[-1 for i in range(w+2)] for i in range(h+2)]
meiro = [["#" for i in range(w+2)]]+[["#"]+list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]
lastnum=[0]
donelist = set()
for i in range(1, h+1):
    for j in range(1, w+1):
        if(meiro[i][j] == "."):
            if(grapht[i-1][j] != -1):
                grapht[i][j] = grapht[i-1][j]
            elif(grapht[i][j-1] != -1):
                grapht[i][j] = grapht[i][j-1]
            elif(grapht[i+1][j] != -1):
                grapht[i][j] = grapht[i+1][j]
            elif(grapht[i][j+1] != -1):
                grapht[i][j] = grapht[i][j+1]
            else:
                grapht[i][j] = lastnum
                graphlist.append(set())
                lastnum = [lastnum[0] + 1]
            if(meiro[i+1][j] == "."):
                grapht[i+1][j] = grapht[i][j]
            if(meiro[i][j+1] == "."):
                if(grapht[i][j+1] == -1):
                    grapht[i][j+1] = grapht[i][j]
                else:
                    donelist.add(grapht[i][j+1][0])
                    graphlist[grapht[i][j][0]] = graphlist[grapht[i][j][0]] | (graphlist[grapht[i][j+1][0]] - set(grapht[i][j]))
                    for k in graphlist[grapht[i][j+1][0]]:
                        graphlist[k].add(grapht[i][j][0])
                    grapht[i][j+1][0] = grapht[i][j][0]
            for k in range(i-2, i+3):
                if(k >= h+1):
                    continue
                for l in range(j-2, j+3):
                    if(l >= w+1):
                        continue
                    if(grapht[k][l] != -1 and grapht[k][l] != grapht[i][j]):
                        graphlist[grapht[i][j][0]].add(grapht[k][l][0])
                        graphlist[grapht[k][l][0]].add(grapht[i][j][0])
start = grapht[ch][cw][0]
end = grapht[dh][dw][0]
donelist = set()
nextlist = queue.Queue()
depthlist = [-1]*len(graphlist)
donelist.add(start)
depthlist[start] = 0
while True:
    for i in graphlist[start]:
        if(i not in donelist):
            nextlist.put(i)
            depthlist[i] = depthlist[start]+1
            donelist.add(i)
    if(nextlist.empty()):
        break
    start = nextlist.get()
#import pprint        
#pprint.pprint(grapht)
#print(graphlist)
print(depthlist[end])

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
graphlist = []
grapht = [[-1 for i in range(w+2)] for i in range(h+2)]
meiro = [["#" for i in range(w+2)]]+[["#"]+list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]
lastnum=[0]
donelist = set()
for i in range(1, h+1):
    for j in range(1, w+1):
        if(meiro[i][j] == "."):
            if(grapht[i-1][j] != -1):
                grapht[i][j] = grapht[i-1][j]
            elif(grapht[i][j-1] != -1):
                grapht[i][j] = grapht[i][j-1]
            elif(grapht[i+1][j] != -1):
                grapht[i][j] = grapht[i+1][j]
            elif(grapht[i][j+1] != -1):
                grapht[i][j] = grapht[i][j+1]
            else:
                grapht[i][j] = lastnum
                graphlist.append(set())
                lastnum = [lastnum[0] + 1]
            if(meiro[i-1][j] == "."):
                if(grapht[i-1][j] == -1):
                    grapht[i-1][j] = grapht[i][j]
                #else:
                    #print(grapht)
                    #grapht[i-1][j][0] = grapht[i][j][0]
                    #print(grapht)
            if(meiro[i][j-1] == "."):
                grapht[i][j-1] = grapht[i][j]
            if(meiro[i+1][j] == "."):
                grapht[i+1][j] = grapht[i][j]
            if(meiro[i][j+1] == "."):
                if(grapht[i][j+1] == -1):
                    grapht[i][j+1] = grapht[i][j]
                else:
                    donelist.add(grapht[i][j+1][0])
                    graphlist[grapht[i][j][0]] = graphlist[grapht[i][j][0]] | (graphlist[grapht[i][j+1][0]] - set(grapht[i][j]))
                    for k in graphlist[grapht[i][j+1][0]]:
                        graphlist[k].add(grapht[i][j][0])
                    grapht[i][j+1][0] = grapht[i][j][0]
            for k in range(i-2, i+3):
                if(k >= h+1):
                    continue
                for l in range(j-2, j+3):
                    if(l >= w+1):
                        continue
                    if(grapht[k][l] != -1 and grapht[k][l] != grapht[i][j]):
                        graphlist[grapht[i][j][0]].add(grapht[k][l][0])
                        graphlist[grapht[k][l][0]].add(grapht[i][j][0])
start = grapht[ch][cw][0]
end = grapht[dh][dw][0]
donelist = set()
nextlist = queue.Queue()
depthlist = [-1]*len(graphlist)
donelist.add(start)
depthlist[start] = 0
while True:
    for i in graphlist[start]:
        if(i not in donelist):
            nextlist.put(i)
            depthlist[i] = depthlist[start]+1
            donelist.add(i)
    if(nextlist.empty()):
        break
    start = nextlist.get()
#import pprint        
#pprint.pprint(grapht)
#print(graphlist)
print(depthlist[end])

Submission status: Wrong Answer

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from collections import deque

h,w=nii()
ch,cw=nii()
ch-=1
cw-=1
dh,dw=nii()
dh-=1
dw-=1
s=[list(input()) for i in range(h)]

dist=[[-1]*w for i in range(h)]

def BFS(que):
  while que:
    y,x=que.popleft()

    if y==dh and x==dw:
      print(dist[y][x])
      exit()

    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and s[ny][nx]!='#':
        que.append((ny,nx))
        s[ny][nx]='#'
        dist[ny][nx]=dist[y][x]
    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 0<=ny<h and 0<=nx<w and s[ny][nx]!='#' and dist[ny][nx]==-1:
        que.append((ny,nx))
        dist[ny][nx]=dist[y][x]+1

dist[ch][cw]=0

que=deque()
que.append((ch,cw))

BFS(que)

print(-1)

Submission status: Wrong Answer

Solution code:
import sys
from heapq import *
from pprint import pprint

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)

def nbs4(i,j):
    for ni,nj in [
                (i-1,j),
        (i,j-1),        (i,j+1),
                (i+1,j),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

def nbs8(i,j):
    for ni,nj in [
        (i-1,j-1),(i-1,j),(i-1,j+1),
        (  i,j-1),        (  i,j+1),
        (i+1,j-1),(i+1,j),(i+1,j+1),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

ans=-1
hp=[(0,si,sj)]
dist=[[float('inf')]*W for _ in range(H)]
dist[si][sj]=0
while hp:
    k,i,j=heappop(hp)
    if i==ti and j==tj:
        if A[i][j]!='#':
            ans=k
        break
    if A[i][j]=='#':
        for ni,nj in nbs8(i,j):
            x=k
            if A[ni][nj]=='#':
                continue
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,ni,nj))
    else:
        for ni,nj in nbs4(i,j):
            x=k
            if A[ni][nj]=='#':
                x=k+1
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,ni,nj))

#pprint(dist)

print(ans)

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
graphlist = []
grapht = [[-1 for i in range(w+2)] for i in range(h+2)]
meiro = [["#" for i in range(w+2)]]+[["#"]+list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]
lastnum=[0]
donelist = set()
for i in range(1, h+1):
    for j in range(1, w+1):
        if(meiro[i][j] == "."):
            if(grapht[i-1][j] != -1):
                grapht[i][j] = grapht[i-1][j]
            elif(grapht[i][j-1] != -1):
                grapht[i][j] = grapht[i][j-1]
            elif(grapht[i+1][j] != -1):
                grapht[i][j] = grapht[i+1][j]
            elif(grapht[i][j+1] != -1):
                grapht[i][j] = grapht[i][j+1]
            else:
                grapht[i][j] = lastnum
                graphlist.append(set())
                lastnum = [lastnum[0] + 1]
            if(meiro[i-1][j] == "."):
                if(grapht[i-1][j] == -1):
                    grapht[i-1][j] = grapht[i][j]
                #else:
                    #print(grapht)
                    #grapht[i-1][j][0] = grapht[i][j][0]
                    #print(grapht)
            if(meiro[i][j-1] == "."):
                grapht[i][j-1] = grapht[i][j]
            if(meiro[i+1][j] == "."):
                grapht[i+1][j] = grapht[i][j]
            if(meiro[i][j+1] == "."):
                if(grapht[i][j+1] == -1):
                    grapht[i][j+1] = grapht[i][j]
                else:
                    donelist.add(grapht[i][j+1][0])
                    graphlist[grapht[i][j][0]] = graphlist[grapht[i][j][0]] | (graphlist[grapht[i][j+1][0]] - set(grapht[i][j]))
                    grapht[i][j+1][0] = grapht[i][j][0]
            for k in range(i-2, i+3):
                if(k >= h+1):
                    continue
                for l in range(j-2, j+3):
                    if(l >= w+1):
                        continue
                    if(grapht[k][l] != -1 and grapht[k][l] != grapht[i][j]):
                        graphlist[grapht[i][j][0]].add(grapht[k][l][0])
                        graphlist[grapht[k][l][0]].add(grapht[i][j][0])
start = grapht[ch][cw][0]
end = grapht[dh][dw][0]
donelist = set()
nextlist = queue.Queue()
depthlist = [-1]*len(graphlist)
donelist.add(start)
depthlist[start] = 0
while True:
    for i in graphlist[start]:
        if(i not in donelist):
            nextlist.put(i)
            depthlist[i] = depthlist[start]+1
            donelist.add(i)
    if(nextlist.empty()):
        break
    start = nextlist.get()
        
#print(grapht)
#print(graphlist)
print(depthlist[end])

Submission status: Wrong Answer

Solution code:
import sys
from heapq import *
from pprint import pprint

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)

def nbs4(i,j):
    for ni,nj in [
                (i-1,j),
        (i,j-1),        (i,j+1),
                (i+1,j),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

def nbs8(i,j):
    for ni,nj in [
        (i-1,j-1),(i-1,j),(i-1,j+1),
        (  i,j-1),        (  i,j+1),
        (i+1,j-1),(i+1,j),(i+1,j+1),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

ans=-1
hp=[(0,0,si,sj)]
dist=[[float('inf')]*W for _ in range(H)]
dist[si][sj]=0
while hp:
    k,w,i,j=heappop(hp)
    if w==1:
        for ni,nj in nbs8(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                continue
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))
    else:
        for ni,nj in nbs4(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                x=k+1
                y=1
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))

#pprint(dist)

print(dist[ti][tj])

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch, cw = map(int, input().split())
dh, dw = map(int, input().split())
graphlist = []
grapht = [[-1 for i in range(w+2)] for i in range(h+2)]
meiro = [["#" for i in range(w+2)]]+[["#"]+list(input())+["#"] for i in range(h)]+[["#" for i in range(w+2)]]
lastnum=[0]
donelist = set()
for i in range(1, h+1):
    for j in range(1, w+1):
        if(meiro[i][j] == "."):
            if(grapht[i-1][j] != -1):
                grapht[i][j] = grapht[i-1][j]
            elif(grapht[i][j-1] != -1):
                grapht[i][j] = grapht[i][j-1]
            elif(grapht[i+1][j] != -1):
                grapht[i][j] = grapht[i+1][j]
            elif(grapht[i][j+1] != -1):
                grapht[i][j] = grapht[i][j+1]
            else:
                grapht[i][j] = lastnum
                graphlist.append(set())
                lastnum = [lastnum[0] + 1]
            if(meiro[i-1][j] == "."):
                if(grapht[i-1][j] == -1):
                    grapht[i-1][j] = grapht[i][j]
                #else:
                    #print(grapht)
                    #grapht[i-1][j][0] = grapht[i][j][0]
                    #print(grapht)
            if(meiro[i][j-1] == "."):
                grapht[i][j-1] = grapht[i][j]
            if(meiro[i+1][j] == "."):
                grapht[i+1][j] = grapht[i][j]
            if(meiro[i][j+1] == "."):
                if(grapht[i][j+1] == -1):
                    grapht[i][j+1] = grapht[i][j]
                else:
                    donelist.add(grapht[i][j+1][0])
                    grapht[i][j+1][0] = grapht[i][j][0]
            for k in range(i-2, i+3):
                if(k >= h+1):
                    continue
                for l in range(j-2, j+3):
                    if(l >= w+1):
                        continue
                    if(grapht[k][l] != -1 and grapht[k][l] != grapht[i][j]):
                        graphlist[grapht[i][j][0]].add(grapht[k][l][0])
                        graphlist[grapht[k][l][0]].add(grapht[i][j][0])
start = grapht[ch][cw][0]
end = grapht[dh][dw][0]
donelist = set()
nextlist = queue.Queue()
depthlist = [-1]*len(graphlist)
donelist.add(start)
depthlist[start] = 0
while True:
    for i in graphlist[start]:
        if(i not in donelist):
            nextlist.put(i)
            depthlist[i] = depthlist[start]+1
            donelist.add(i)
    if(nextlist.empty()):
        break
    start = nextlist.get()
        
#print(graphlist)
print(depthlist[end])

Submission status: Wrong Answer

Solution code:
import sys
from heapq import *
from pprint import pprint

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)

def nbs4(i,j):
    for ni,nj in [
                (i-1,j),
        (i,j-1),        (i,j+1),
                (i+1,j),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

def nbs8(i,j):
    for ni,nj in [
        (i-1,j-1),(i-1,j),(i-1,j+1),
        (  i,j-1),        (  i,j+1),
        (i+1,j-1),(i+1,j),(i+1,j+1),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

ans=-1
hp=[(0,0,si,sj)]
dist=[[float('inf')]*W for _ in range(H)]
dist[si][sj]=0
while hp:
    k,w,i,j=heappop(hp)
    if i==ti and j==tj:
        ans=k
        break
    if w==1:
        for ni,nj in nbs8(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                continue
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))
    else:
        for ni,nj in nbs4(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                x=k+1
                y=1
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))

#pprint(dist)

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import *
from pprint import pprint

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

def nbs4(i,j):
    for ni,nj in [
                (i-1,j),
        (i,j-1),        (i,j+1),
                (i+1,j),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

def nbs8(i,j):
    for ni,nj in [
        (i-1,j-1),(i-1,j),(i-1,j+1),
        (  i,j-1),        (  i,j+1),
        (i+1,j-1),(i+1,j),(i+1,j+1),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

ans=-1
hp=[(0,0,si,sj)]
dist=[[float('inf')]*W for _ in range(H)]
dist[si][sj]=0
while hp:
    k,w,i,j=heappop(hp)
    if i==ti and j==tj:
        ans=k
        break
    if w==1:
        for ni,nj in nbs8(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                continue
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))
    else:
        for ni,nj in nbs4(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                x=k+1
                y=1
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))

#pprint(dist)

print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import *
from pprint import pprint

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

def nbs4(i,j):
    for ni,nj in [
                (i-1,j),
        (i,j-1),        (i,j+1),
                (i+1,j),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

def nbs8(i,j):
    for ni,nj in [
        (i-1,j-1),(i-1,j),(i-1,j+1),
        (  i,j-1),        (  i,j+1),
        (i+1,j-1),(i+1,j),(i+1,j+1),
    ]:
        if 0<=ni<H and 0<=nj<W:
            yield ni,nj

ans=-1
hp=[(0,0,si,sj)]
dist=[[1000]*W for _ in range(H)]
dist[si][sj]=0
while hp:
    k,w,i,j=heappop(hp)
    if i==ti and j==tj:
        ans=k
        break
    if w==1:
        for ni,nj in nbs8(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                continue
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))
    else:
        for ni,nj in nbs4(i,j):
            x,y=k,0
            if A[ni][nj]=='#':
                x=k+1
                y=1
            if x>=dist[ni][nj]:
                continue
            dist[ni][nj]=x
            heappush(hp,(x,y,ni,nj))

#pprint(dist)

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict, deque

H,W=map(int, sys.stdin.readline().split())
CH,CW=map(int, sys.stdin.readline().split())
CH-=1
CW-=1
DH,DW=map(int, sys.stdin.readline().split())
DH-=1
DW-=1
S=[ sys.stdin.readline().strip() for _ in range(H) ]

D=[(0,1),(0,-1),(1,0),(-1,0)]
WARP=[]
for dh in range(-2,3):
    for dw in range(-2,3):
        if abs(dh)+abs(dw)<=1: continue
        WARP.append((dh,dw))

d=defaultdict(lambda: float("inf")) #スタート地点から各マスまでの距離

q=deque()
q.append((CH,CW))
d[(CH,CW)]=0

while q:
    fro_h, fro_w=q.popleft()
    for dh,dw in D:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]<d[(to_h, to_w)]:
            if d[(to_h, to_w)]==float("inf"):
                q.appendleft((to_h, to_w))
            d[(to_h, to_w)]=d[(fro_h, fro_w)]
            
    for dh,dw in WARP:
        to_h, to_w=fro_h+dh, fro_w+dw
        if 0<=to_h<H and 0<=to_w<W and S[to_h][to_w]=="." and d[(fro_h, fro_w)]+1<d[(to_h, to_w)]:
            if d[(to_h, to_w)]==float("inf"):
                q.append((to_h, to_w))
            d[(to_h, to_w)]=d[(fro_h, fro_w)]+1

if d[(DH,DW)]==float("inf"):
    print -1
else:
    print d[(DH,DW)]