import sys
from collections import deque
def solution():
INPUT = lambda: sys.stdin.readline().rstrip()
READINTS = lambda: list(map(int, INPUT().split()))
R, C = READINTS()
G = [READINTS() for _ in range(R)]
SR, SC, SF = [v-1 for v in READINTS()]
ER, EC, EF = [v-1 for v in READINTS()]
K = 3
F, FR, FC = 4, [0, 0, 1, -1], [1, -1, 0, 0]
NF = [[2, 3], [2, 3], [0, 1], [0, 1]]
D = [[[-1]*F for _ in range(C)] for _ in range(R)]
q = deque()
D[SR][SC][SF] = 0
q.append((SR, SC, SF))
while q:
r, c, f = q.popleft()
if r==ER and c==EC and f==EF:
return D[ER][EC][EF]
for k in range(1, K+1):
nr, nc = r+FR[f]*k, c+FC[f]*k
if nr<0 or nr>=R or nc<0 or nc>=C:
continue
if G[nr][nc]:
break
if D[nr][nc][f]>=0:
continue
D[nr][nc][f] = D[r][c][f]+1
q.append((nr, nc, f))
for nf in NF[f]:
if D[r][c][nf]==-1:
D[r][c][nf] = D[r][c][f]+1
q.append((r, c, nf))
return 0
print(solution())
Leave a comment