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:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

from collections import deque
import heapq
INF = 10**18

def dijkstra(start, G):
    done = [False]*(len(G))
    dist = [INF]*(len(G))
    dist[start] = 0
    h = []
    heapq.heappush(h, [0, start])
    while h:
        _, cur = heapq.heappop(h)
        if done[cur]: continue
        done[cur] = True
        for to, cost in G[cur]:
            if dist[cur]+cost < dist[to]:
                dist[to] = dist[cur]+cost
                heapq.heappush(h, [dist[to], to])
    return dist

H, W = map(int, input().split())
sh, sw = map(lambda x: int(x)-1, input().split())
gh, gw = map(lambda x: int(x)-1, input().split())
S = [input() for _ in range(H)]
done = [[-1]*W for _ in range(H)]
q = deque()
num = 0
for ii in range(H):
    for jj in range(W):
        if done[ii][jj] != -1: continue
        q.append((ii, jj))
        done[ii][jj] = num
        while q:
            h, w = q.popleft()
            for dh, dw in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                nh, nw = h+dh, w+dw
                if not (0 <= nh < H and 0 <= nw < W and S[nh][nw] == "."):
                    continue
                if done[nh][nw] == -1:
                    q.append((nh, nw))
                    done[h][w] = num
        num += 1
G = [[] for _ in range(num)]
done2 = [[False]*num for _ in range(num)]
for h in range(H):
    for w in range(W):
        if S[h][w] != ".": continue
        fr = done[h][w]
        for ii in range(-2, 3):
            for jj in range(-2, 3):
                nh, nw = h+ii, w+jj
                if not (0 <= nh < H and 0 <= nw < W and S[nh][nw] == "."):
                    continue
                to = done[nh][nw]
                if fr != to and (not done2[fr][to]):
                    done2[fr][to] = True
                    done2[to][fr] = True
                    G[fr].append((to, 1))
                    G[to].append((fr, 1))
D = dijkstra(done[sh][sw], G)
ans = D[done[gh][gw]]
if ans != INF:
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

h, w = map(int, input().split())
si, sj = map(int, input().split())
ti, tj = map(int, input().split())
s = [input() for _ in range(h)]
si -= 1
sj -= 1
ti -= 1
tj -= 1

INF = 10**9
di = [-1, 0, 1, 0]
dj = [0, -1, 0, 1]
dist = [[INF] * w] * h
q = deque()
dist[si][sj] = 0
q.appendleft([si, sj])

while q:
    i, j = q.popleft()
    d = dist[i][j]
    for v in range(4):
        ni = i + di[v]
        nj = 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.appendleft([ni, nj])
    for ei in range(-2, 3):
        for ej in range(-2, 3):
            ni = i + ei
            nj = 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+1: continue
            dist[ni][nj] = d+1
            q.append([ni, nj])

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

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

visit = [[-1 for w in range(W)] for h in range(H)]

ch, cw = ch - 1, cw - 1
dh, dw = dh - 1, dw - 1

nextQ = {ch*1000 + cw}
visit[ch][cw] = 0
while len(nextQ)>0:
  Q = deque(nextQ)
  nextQ = set()
  while len(Q)>0:
  #print(Q)
    hw = Q.popleft()
    h = hw // 1000
    w = hw % 1000
    for dy in range(-min(2,h), min(3, H-h)):
      for dx in range(-min(2,w), min(3, W-w)):
        if dx==0 and dy==0:
          continue
        nh = h + dy
        nw = w + dx
        if (dx==0 and abs(dy)==1) or (dy==0 and abs(dx)==1):
          #print(nh, nw, visit[h][w])
          if f[nh][nw]:
            if visit[nh][nw] == -1:
            #print(1, nh, nw, visit[h][w])
              visit[nh][nw] = visit[h][w]
              Q.append(nh*1000+nw)
            elif visit[nh][nw] > visit[h][w]:
              #print(2, nh, nw, visit[h][w])
              visit[nh][nw] = visit[h][w]
              nextQ -= {nh*1000+nw}
        else:
          if f[nh][nw]:
            if visit[nh][nw] == -1:
            #print(3, nh, nw, visit[h][w])
              visit[nh][nw] = visit[h][w] + 1
              nextQ.add(nh*1000+nw)

print(visit[dh][dw])

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

visit = [[-1 for w in range(W)] for h in range(H)]

ch, cw = ch - 1, cw - 1
dh, dw = dh - 1, dw - 1

Q = deque([ch*1000 + cw])
visit[ch][cw] = 0

while len(Q)>0:
  #print(Q)
  hw = Q.popleft()
  h = hw // 1000
  w = hw % 1000
  for dy in range(-min(2,h), min(3, H-h)):
    for dx in range(-min(2,w), min(3, W-w)):
      if dx==0 and dy==0:
        continue
      nh = h + dy
      nw = w + dx
      if (dx==0 and abs(dy)==1) or (dy==0 and abs(dx)==1):
        #print(nh, nw, visit[h][w])
        if f[nh][nw]:
          if visit[nh][nw] == -1:
            #print(1, nh, nw, visit[h][w])
            visit[nh][nw] = visit[h][w]
            Q.appendleft(nh*1000+nw)
          elif visit[nh][nw] > visit[h][w]:
            #print(2, nh, nw, visit[h][w])
            visit[nh][nw] = visit[h][w]
      else:
        if f[nh][nw]:
          if visit[nh][nw] == -1:
            #print(3, nh, nw, visit[h][w])
            visit[nh][nw] = visit[h][w] + 1
            Q.append(nh*1000+nw)

print(visit[dh][dw])

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

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

icase=0
if icase==0:
    h,w=map(int,input().split())
    ch,cw=map(int,input().split())
    ch-=1
    cw-=1
    dh,dw=map(int,input().split())
    dh-=1
    dw-=1
    s=[[] for i in range(h)]
    for i in range(h):
        s[i]=input()
        
ij=[(1,0),(-1,0),(0,1),(0,-1)]
wpij=[(1,1),(-1,-1),(-1,1),(1,-1),
      (2,-2),(2,-1),(2,0),(2,1),(2,2),
      (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),
      (1,2),(0,2),(-1,2),(1,-2),(0,-2),(-1,-2)]

g=[[[] for i in range(w)] for i in range(h)]
gg=[[[] for i in range(w)] for i in range(h)]
wpg2=[[0]*w for i in range(h)]
wpg=[]
for i in range(h):
    for j in range(w):
        for ii,jj in ij:
            if 0>i+ii or i+ii>=h:
                continue
            if 0>j+jj or j+jj>=w:
                continue
            if s[i+ii][j+jj]==".":
                g[i][j].append((i+ii,j+jj))        
            else:
#                wpg.append((i,j))
                wpg2[i][j]=1
print(-2)                
for i in range(h):
    for j in range(w):
        if wpg2[i][j]==1:
            wpg.append((i,j))
                
#wpg=tuple(set(wpg))

for i,j in wpg:
    for ii,jj in wpij:
         if 0<=i+ii and i+ii<h and 0<=j+jj \
            and j+jj<w and s[i+ii][j+jj]==".":
                gg[i][j].append((i+ii,j+jj))        

q=deque([(ch,cw)])
qq=deque()
parent=[[-1]*w for i in range(h)]
parent[ch][cw]=0
dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0
while True:
    while q:
#        print("q1:",q)
        hi,wi = q.popleft()
        if len(gg[hi][wi])>0:
            qq.append((hi,wi))
        for hj,wj in g[hi][wi]:
            if parent[hj][wj] !=-1:
                continue
            else:
                parent[hj][wj]=(hi,wi)
                dist[hj][wj]=dist[hi][wi]+1
                q.append((hj,wj))
                if hj==dh and wj==dw:
                    print(dist[dh][dw]//(10**7))   
                    sys.exit()

    while qq:
        hi,wi = qq.popleft()
        for hj,wj in gg[hi][wi]:
            if parent[hj][wj]!=-1:
                continue
            parent[hj][wj]=(hi,wi)
            dist[hj][wj]=dist[hi][wi]+10**7
            q.append((hj,wj))
            if hj==dh and wj==dw:
                print(dist[dh][dw]//(10**7))   
                sys.exit()

    if len(q)==0:
        break
print(-1)

Submission status: Wrong Answer

Solution code:
def num():
    h, w = map(int, input().split())
    c0, c1 = map(int, input().split())
    d0, d1 = map(int, input().split())
    s = [["#"]*(w+4)]*2+[["#"]*2+list(input())+["#"]*2 for _ in range(h)]+[["#"]*(w+4)]*2
    q = [(c0+1, c1+1, 0)]
    q1 = []
    ans = -1
    move = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)]+move]
    
    while q:
        a0, a1, a2 = q.pop()
        q1.append([a0, a1, a2])
        s[a0][a1] = '#'
        if a0 == d0+1 and a1 == d1+1:
            ans = a2
            break

        for i, j in move:
            x, y = a0+i, a1+j
            if s[x][y] == '.':
                q.append((x, y, a2))
        if len(q) == 0:
            while q1:
                a0, a1, a2 = q1.pop()
                for x, y in warp:
                    x, y = a0+i, a1+j
                    if s[x][y] == '.':
                        q.append((x, y, a2+1))    
    print(ans)

if __name__ == "__main__":
    num()

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

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

icase=0
if icase==0:
    h,w=map(int,input().split())
    ch,cw=map(int,input().split())
    ch-=1
    cw-=1
    dh,dw=map(int,input().split())
    dh-=1
    dw-=1
    s=[[] for i in range(h)]
    for i in range(h):
        s[i]=input()
        
ij=[(1,0),(-1,0),(0,1),(0,-1)]
wpij=[(1,1),(-1,-1),(-1,1),(1,-1),
      (2,-2),(2,-1),(2,0),(2,1),(2,2),
      (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),
      (1,2),(0,2),(-1,2),(1,-2),(0,-2),(-1,-2)]

g=[[[] for i in range(w)] for i in range(h)]
gg=[[[] for i in range(w)] for i in range(h)]
wpg=[]
for i in range(h):
    for j in range(w):
        for ii,jj in ij:
            if 0<=i+ii and i+ii<h and 0<=j+jj and \
                j+jj<w and s[i+ii][j+jj]==".":
                g[i][j].append((i+ii,j+jj))        
            if 0<=i+ii and i+ii<h and 0<=j+jj and \
                j+jj<w and s[i+ii][j+jj]=="#":
#                if not ((i,j) in wpg):
#                    wpg.append((i,j))        
                wpg.append((i,j))        
print(-2)
wpg=tuple(set(wpg))
for i,j in wpg:
    for ii,jj in wpij:
         if 0<=i+ii and i+ii<h and 0<=j+jj \
            and j+jj<w and s[i+ii][j+jj]==".":
                gg[i][j].append((i+ii,j+jj))        

q=deque([(ch,cw)])
qq=deque()
parent=[[-1]*w for i in range(h)]
parent[ch][cw]=0
dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0
while True:
    while q:
#        print("q1:",q)
        hi,wi = q.popleft()
        if len(gg[hi][wi])>0:
            qq.append((hi,wi))
        for hj,wj in g[hi][wi]:
            if parent[hj][wj] !=-1:
                continue
            else:
                parent[hj][wj]=(hi,wi)
                dist[hj][wj]=dist[hi][wi]+1
                q.append((hj,wj))
                if hj==dh and wj==dw:
                    print(dist[dh][dw]//(10**7))   
                    sys.exit()

    while qq:
        hi,wi = qq.popleft()
        for hj,wj in gg[hi][wi]:
            if parent[hj][wj]!=-1:
                continue
            parent[hj][wj]=(hi,wi)
            dist[hj][wj]=dist[hi][wi]+10**7
            q.append((hj,wj))
            if hj==dh and wj==dw:
                print(dist[dh][dw]//(10**7))   
                sys.exit()

    if len(q)==0:
        break
print(-1)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

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

icase=0
if icase==0:
    h,w=map(int,input().split())
    ch,cw=map(int,input().split())
    ch-=1
    cw-=1
    dh,dw=map(int,input().split())
    dh-=1
    dw-=1
    s=[[] for i in range(h)]
    for i in range(h):
        s[i]=input()
        
ij=[(1,0),(-1,0),(0,1),(0,-1)]
wpij=[(1,1),(-1,-1),(-1,1),(1,-1),
      (2,-2),(2,-1),(2,0),(2,1),(2,2),
      (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2),
      (1,2),(0,2),(-1,2),(1,-2),(0,-2),(-1,-2)]

g=[[[] for i in range(w)] for i in range(h)]
gg=[[[] for i in range(w)] for i in range(h)]
wpg=[]
for i in range(h):
    for j in range(w):
        for ii,jj in ij:
            if 0<=i+ii and i+ii<h and 0<=j+jj and \
                j+jj<w and s[i+ii][j+jj]==".":
                g[i][j].append((i+ii,j+jj))        
            if 0<=i+ii and i+ii<h and 0<=j+jj and \
                j+jj<w and s[i+ii][j+jj]=="#":
#                if not ((i,j) in wpg):
#                    wpg.append((i,j))        
                wpg.append((i,j))        

wpg=tuple(set(wpg))
print(-2)
for i,j in wpg:
    for ii,jj in wpij:
         if 0<=i+ii and i+ii<h and 0<=j+jj \
            and j+jj<w and s[i+ii][j+jj]==".":
                gg[i][j].append((i+ii,j+jj))        

q=deque([(ch,cw)])
qq=deque()
parent=[[-1]*w for i in range(h)]
parent[ch][cw]=0
dist=[[-1]*w for i in range(h)]
dist[ch][cw]=0
while True:
    while q:
#        print("q1:",q)
        hi,wi = q.popleft()
        if len(gg[hi][wi])>0:
            qq.append((hi,wi))
        for hj,wj in g[hi][wi]:
            if parent[hj][wj] !=-1:
                continue
            else:
                parent[hj][wj]=(hi,wi)
                dist[hj][wj]=dist[hi][wi]+1
                q.append((hj,wj))
                if hj==dh and wj==dw:
                    print(dist[dh][dw]//(10**7))   
                    sys.exit()

    while qq:
        hi,wi = qq.popleft()
        for hj,wj in gg[hi][wi]:
            if parent[hj][wj]!=-1:
                continue
            parent[hj][wj]=(hi,wi)
            dist[hj][wj]=dist[hi][wi]+10**7
            q.append((hj,wj))
            if hj==dh and wj==dw:
                print(dist[dh][dw]//(10**7))   
                sys.exit()

    if len(q)==0:
        break
print(-1)

Submission status: Wrong Answer

Solution code:
h,w = map(int, input().split())

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

s = [[] for _ in range(h)]
for i in range(h):
    s[i] = input()

print(s)

from collections import deque
d = deque()

visited = [[False]*w for _ in range(h)]

d.append([sy,sx,0])

while len(d) > 0:
    y,x,c = d.popleft()
    
    if visited[y][x] is True:
        continue
    
    if gy == y and gx == x:
        print(c)
        exit(0)

    dxy = [[1,0], [-1, 0], [0, 1], [0, -1]]
    for dx, dy in dxy:
        nx = dx + x
        ny = dy + y
        if nx < 0 or nx >= w or ny < 0 or ny >= h:
            continue
        if s[ny][nx] == "#":
            continue
        if visited[ny][nx] is True:
            continue
        d.appendleft([ny, nx, c])

    for dy in range(-2, 3):
        for dy in range(-2, 3):
            nx = dx + x
            ny = dy + y
            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue
            if s[ny][nx] == "#":
                continue
            if visited[ny][nx] is True:
                continue
            d.append([ny, nx, c+1])

print(-1)

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch = list(map(int, input().split()))
dh = list(map(int, input().split()))
s = [list(input()) for _ in range(h)]

q = queue.Queue()
q.put([ch[0]-1, ch[1]-1, 0])
ans = float('inf')

while not q.empty():
    a = q.get()
    s[a[0]][a[1]] = '#'
    if a[2] >= ans:
        continue
    if a[0] == dh[0]-1 and a[1] == dh[1]-1:
        ans = min(ans, a[2])

    for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1),
                 (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)):
        x, y = a[0]+i, a[1]+j
        if 0 <= x < h and 0 <= y < w:
            if s[x][y] == '.':
                if abs(i)+abs(j) <= 1:
                    q.put([x, y, a[2]])
                else:
                    q.put([x, y, a[2]+1])

if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
import queue
h, w = map(int, input().split())
ch = list(map(int, input().split()))
dh = list(map(int, input().split()))
s = [list(input()) for _ in range(h)]

q = queue.Queue()
q.put([ch[0]-1, ch[1]-1, 0])
ans = float('inf')

while not q.empty():
    a = q.get()
    s[a[0]][a[1]] = '#'
    if a[2] >= ans:
        continue
    if a[0] == dh[0]-1 and a[1] == dh[1]-1:
        ans = min(ans, a[2])

    for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        x, y = a[0]+i, a[1]+j
        if 0 <= x < h and 0 <= y < w:
            if s[x][y] == '.':
                q.put([x, y, a[2]])

    for i, j 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)):
        x, y = a[0]+i, a[1]+j
        if 0 <= x < h and 0 <= y < w:
            if s[x][y] == '.':
                q.put([x, y, a[2]+1])

if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
import queue

def main():
    h,w = map(int,input().split())
    Ch,Cw = map(lambda x:int(x)+1,input().split())
    Dh, Dw = map(lambda x:int(x)+1,input().split())

    maze = []
    for i in range(2):
        maze.append(['#' for j in range(4+w)])
    for i in range(h):
        maze.append(['#' for j in range(2)]+list(input())+ ['#' for j in range(2)])
    for i in range(2):
        maze.append(['#' for j in range(4+w)])

    # for i in range(len(maze)):
    #     print(''.join(maze[i]))

    maze_separate = [[0 for i in range(len(maze[0]))] for j in range(len(maze))]
    number = 1
    for i in range(len(maze_separate)):
        for j in range(len(maze_separate[i])):
            if maze[i][j]=='.' and maze_separate[i][j]==0:
                maze_separate[i][j] = number
                number += 1
                q = queue.Queue()
                q.put([i,j])
                while not q.empty():
                    x,y = q.get()
                    for dx,dy in [(0,1),(1,0),(0,-1),(-1,0)]:
                        if maze[x+dx][y+dy] == '.' and maze_separate[x+dx][y+dy]==0:
                            maze_separate[x+dx][y+dy] = maze_separate[x][y]
                            q.put([x+dx,y+dy])

    # for i in range(len(maze_separate)):
    #     print(maze_separate[i])

    have_been = [False for i in range(number+3)]
    have_been[0] = True
    have_been[maze_separate[Ch][Cw]] = True

    maze[Ch][Cw] = '#'
    q = queue.Queue()
    q.put([Ch,Cw,0])
    while not q.empty():
        x,y,cnt = q.get()
        # print(x,y,cnt)
        if x==Dh and y == Dw:
            print(cnt)
            return 
        else:
            for dx,dy in [(0,1),(1,0),(0,-1),(-1,0)]:
                if maze[x+dx][y+dy] == '.':
                   maze[x+dx][y+dy] = '#'
                   q.put([x+dx,y+dy,cnt]) 
            for dx in range(-2,3):
                for dy in range(-2,3):
                    if maze[x+dx][y+dy] == '.' and maze_separate[x+dx][y+dy] != maze_separate[x][y] and have_been[maze_separate[x+dx][y+dy]] == False:
                        have_been[maze_separate[x+dx][y+dy]] = True
                        maze[x+dx][y+dy] = '#'
                        q.put([x+dx,y+dy,cnt+1]) 
    print(-1)
    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import queue

def main():
    h,w = map(int,input().split())
    Ch,Cw = map(lambda x:int(x)+1,input().split())
    Dh, Dw = map(lambda x:int(x)+1,input().split())

    maze = []
    for i in range(2):
        maze.append(['#' for j in range(4+w)])
    for i in range(h):
        maze.append(['#' for j in range(2)]+list(input())+ ['#' for j in range(2)])
    for i in range(2):
        maze.append(['#' for j in range(4+w)])

    # for i in range(len(maze)):
    #     print(''.join(maze[i]))

    maze_separate = [[0 for i in range(len(maze[0]))] for j in range(len(maze))]
    number = 1
    for i in range(len(maze_separate)):
        for j in range(len(maze_separate[i])):
            if maze[i][j]=='.' and maze_separate[i][j]==0:
                maze_separate[i][j] = number
                number += 1
                q = queue.Queue()
                q.put([i,j])
                while not q.empty():
                    x,y = q.get()
                    for dx,dy in [(0,1),(1,0),(0,-1),(-1,0)]:
                        if maze[x+dx][y+dy] == '.' and maze_separate[x+dx][y+dy]==0:
                            maze_separate[x+dx][y+dy] = maze_separate[x][y]
                            q.put([x+dx,y+dy])

    # for i in range(len(maze_separate)):
    #     print(maze_separate[i])

    have_been = [False for i in range(number)]
    have_been[0] = True
    have_been[maze_separate[Ch][Cw]] = True

    q = queue.Queue()
    q.put([Ch,Cw,0])
    while not q.empty():
        x,y,cnt = q.get()
        # print(x,y,cnt)
        if x==Dh and y == Dw:
            print(cnt)
            return 
        else:
            for dx,dy in [(0,1),(1,0),(0,-1),(-1,0)]:
                if maze[x+dx][y+dy] == '.':
                   maze[x+dx][y+dy] = '#'
                   q.put([x+dx,y+dy,cnt]) 
            for dx in range(-2,3):
                for dy in range(-2,3):
                    if maze[x+dx][y+dy] == '.' and maze_separate[x+dx][y+dy] != maze_separate[x][y] and have_been[maze_separate[x+dx][y+dy]] == False:
                        have_been[maze_separate[x+dx][y+dy]] = True
                        q.put([x+dx,y+dy,cnt+1]) 
    print(-1)
    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import queue

def main():
    h,w = map(int,input().split())
    Ch,Cw = map(lambda x:int(x)+1,input().split())
    Dh, Dw = map(lambda x:int(x)+1,input().split())

    maze = []
    for i in range(2):
        maze.append(['#' for j in range(4+w)])
    for i in range(h):
        maze.append(['#' for j in range(2)]+list(input())+ ['#' for j in range(2)])
    for i in range(2):
        maze.append(['#' for j in range(4+w)])

    # for i in range(len(maze)):
    #     print(''.join(maze[i]))

    maze_separate = [[0 for i in range(len(maze[0]))] for j in range(len(maze))]
    number = 1
    for i in range(len(maze_separate)):
        for j in range(len(maze_separate[i])):
            if maze[i][j]=='.' and maze_separate[i][j]==0:
                maze_separate[i][j] = number
                number += 1
                q = queue.Queue()
                q.put([i,j])
                while not q.empty():
                    x,y = q.get()
                    for dx,dy in [(0,1),(1,0),(0,-1),(-1,0)]:
                        if maze[x+dx][y+dy] == '.' and maze_separate[x+dx][y+dy]==0:
                            maze_separate[x+dx][y+dy] = maze_separate[x][y]
                            q.put([x+dx,y+dy])

    # for i in range(len(maze_separate)):
    #     print(maze_separate[i])

    have_been = [False for i in range(number)]

    q = queue.Queue()
    q.put([Ch,Cw,0])
    while not q.empty():
        x,y,cnt = q.get()
        # print(x,y,cnt)
        if x==Dh and y == Dw:
            print(cnt)
            return 
        else:
            for dx,dy in [(0,1),(1,0),(0,-1),(-1,0)]:
                if maze[x+dx][y+dy] == '.':
                   maze[x+dx][y+dy] = '#'
                   q.put([x+dx,y+dy,cnt]) 
            for dx in range(-2,3):
                for dy in range(-2,3):
                    if maze[x+dx][y+dy] == '.' and maze_separate[x+dx][y+dy] != maze_separate[x][y] and have_been[maze_separate[x+dx][y+dy]] == False:
                        have_been[maze_separate[x+dx][y+dy]] = True
                        q.put([x+dx,y+dy,cnt+1]) 
    print(-1)
    

    return

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#ABC176
#D - Wizard in Maze
h,w=map(int,input().split())
ch,cw=map(int,input().split())
dh,dw=map(int,input().split())
b=[ch-1,cw-1]
a,c,d,f,g=[],[],[],[],[]
c.append(b)
d.append(b)
g.append(b)
x=0

for i in range(h):
  a.append(list(input()))

warp=0

while len(c)>0:
  ch,cw=c[0]
  c.pop(0)
  if ch==dh-1 and cw==dw-1:
    print(warp)
    x=1
    c=[]
  else:
    e=[[ch-1,cw],[ch+1,cw],[ch,cw-1],[ch,cw+1]]
    for i in e:
      ch1,cw1=i
      if i not in d and 0<=ch1<h and 0<=cw1<w and  a[ch1][cw1]==".":
        c.append(i)
        d.append(i)
        g.append(i)

    if len(c)==0:
      warp=warp+1
      for i in g:
        ch1,cw1=i
        for j in range(5):
          ch0=ch1-2+j
          if 0<=ch0<h:
            for k in range(5):
              cw0=cw1-2+k
              l=[ch0,cw0]
              if l not in d and 0<=cw0<w and a[ch0][cw0]==".":
                c.append(i)
                d.append(i)
      g=[]
if x!=1:
  print(-1)

Submission status: Wrong Answer

Solution code:
#ABC176
#D - Wizard in Maze
h,w=map(int,input().split())
ch,cw=map(int,input().split())
dh,dw=map(int,input().split())
b=[ch-1,cw-1]
a,c,d,f,g=[],[],[],[],[]
c.append(b)
d.append(b)
x=0

for i in range(h):
  a.append(list(input()))

warp=0

while len(c)>0:
  ch,cw=c[0]
  c.pop(0)
  if ch==dh-1 and cw==dw-1:
    print(warp)
    x=1
    c=[]
  else:
    e=[[ch-1,cw],[ch+1,cw],[ch,cw-1],[ch,cw+1]]
    for i in e:
      ch1,cw1=i
      if i not in d and 0<=ch1<h and 0<=cw1<w and  a[ch1][cw1]==".":
        c.append(i)
        d.append(i)
        g.append(i)

    if len(c)==0:
      warp=warp+1
      for i in g:
        ch1,cw1=i
        for j in range(5):
          ch0=ch1-2+j
          if 0<=ch0<h:
            for k in range(5):
              cw0=cw1-2+k
              l=[ch0,cw0]
              if l not in d and 0<=cw0<w and a[ch0][cw0]==".":
                c.append(l)
                d.append(l)
      g=[]

if x!=1:
  print(-1)

Submission status: Wrong Answer

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
H,W=map(int,input().split())
cx,cy=map(lambda x: int(x)+1,input().split())
dx,dy=map(lambda x: int(x)+1,input().split())
S=["#"*(W+4)]*2+["##"+input()+"##" for i in range(H)]+["#"*(W+4)]*2
l=[[-2]*(W+4) for i in range(H+4)]
for i in range(2,H+2):
    for j in range(2,W+2):
        if S[i][j]==".":
            l[i][j]=-1
l[cx][cy]=0
b=[(cx,cy)]
bb=[(cx,cy)]
t=0
while bb:
    while b:
        a=[]
        for i in b:
            if l[i[0]+1][i[1]]==-1:
                l[i[0]+1][i[1]]=t
                a.append((i[0]+1,i[1]))
            if l[i[0]-1][i[1]]==-1:
                l[i[0]-1][i[1]]=t
                a.append((i[0]-1,i[1]))
            if l[i[0]][i[1]+1]==-1:
                l[i[0]][i[1]+1]=t
                a.append((i[0],i[1]+1))
            if l[i[0]][i[1]-1]==-1:
                l[i[0]][i[1]-1]=t
                a.append((i[0],i[1]-1))
        bb+=a
        b=a
    aa=[]
    t+=1
    for i in bb:
        for j in range(-2,3):
            for k in range(-2,3):
                if l[i[0]+j][i[1]+k]==-1:
                    l[i[0]+j][i[1]+k]=t
                    aa.append((i[0]+j,i[1]+k))
    if l[dx][dy]>=0:
        break
    bb=aa
print(l[dx][dy])

Submission status: Wrong Answer

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
H,W=map(int,input().split())
cx,cy=map(lambda x: int(x)+1,input().split())
dx,dy=map(lambda x: int(x)+1,input().split())
S=["#"*(W+4)]*2+["##"+input()+"##" for i in range(H)]+["#"*(W+4)]*2
l=[[-2]*(W+4) for i in range(H+4)]
for i in range(2,H+2):
    for j in range(2,W+2):
        if S[i][j]==".":
            l[i][j]=-1
l[cx][cy]=0
b=[(cx,cy)]
bb=[(cx,cy)]
t=0
while bb:
    while b:
        a=[]
        for i in b:
            if l[i[0]+1][i[1]]==-1:
                l[i[0]+1][i[1]]=t
                a.append((i[0]+1,i[1]))
            if l[i[0]-1][i[1]]==-1:
                l[i[0]-1][i[1]]=t
                a.append((i[0]-1,i[1]))
            if l[i[0]][i[1]+1]==-1:
                l[i[0]][i[1]+1]=t
                a.append((i[0],i[1]+1))
            if l[i[0]][i[1]-1]==-1:
                l[i[0]][i[1]-1]=t
                a.append((i[0],i[1]-1))
        bb+=a
        b=a
    aa=[]
    t=1
    for i in bb:
        for j in range(-2,3):
            for k in range(-2,3):
                if l[i[0]+j][i[1]+k]==-1:
                    l[i[0]+j][i[1]+k]=t
                    aa.append((i[0]+j,i[1]+k))
    if l[dx][dy]>=0:
        break
    bb=aa
print(l[dx][dy])

Submission status: Wrong Answer

Solution code:
from collections import deque

def solve(h, w, ch, cw, dh, dw, s):
    G = [[0]*w for r in range(h)]
    label = 0
    for r in range(h):
        for c in range(w):
            if (s[r][c] == '.') and (G[r][c] == 0):
                label += 1
                que = deque([(r, c)])
                G[r][c] = label
                while que:
                    cr, cc = que.popleft()
                    for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                        nr, nc = cr+dr, cc+dc
                        if (0 <= nr < h) and (0 <= nc < w) and (s[nr][nc] == ".") and (G[nr][nc] == 0):
                            G[nr][nc] = label
                            que.append((nr, nc))

    sr, sc = ch-1, cw-1
    tr, tc = dh-1, dw-1

    neighbors = [(dr, dc) for dc in range(-2, 3) for dr in range(-2, 3) if abs(dr) + abs(dc) > 0]
    used = [[(s[r][c] == "#") for c in range(w)] for r in range(h)]
    que = deque([(sr, sc, 0)])
    used[sr][sc] = True
    while que:
        cr, cc, n = que.popleft()
        if (cr == tr) and (cc == tc):
            return n
        for dr, dc in neighbors:
            nr, nc = cr+dr, cc+dc
            if (0 <= nr < h) and (0 <= nc < w) and not used[nr][nc]:
                used[nr][nc] = True
                if G[nr][nc] == G[cr][cc]: # 同一グループ
                    que.appendleft((nr, nc, n))
                else:
                    que.append((nr, nc, n+1))
    return -1

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