from collections import deque import sys input = sys.stdin.readline def sieve(n): is_prime = [True]*(n+1) if n >= 0: is_prime[0] = False if n >= 1: is_prime[1] = False for i in range(2, int(n**0.5)+1): if is_prime[i]: for j in range(i*i, n+1, i): is_prime[j] = False return is_prime def find_shift(c0, d0, can_loop, is_prime, LIMIT): if not can_loop: return 0 if c0<=LIMIT and d0<=LIMIT and is_prime[c0] and is_prime[d0] else None for x in range(LIMIT+1): if is_prime[c0+x] and is_prime[d0+x]: return x return None def bfs_with_mask(H, W, grid, Sx, Sy, Gx, Gy, need_v, need_h, DIRS): # build state‐tuple factory def make_state(x, y, uv, uh): if need_v and need_h: return (x,y,uv,uh) if need_v: return (x,y,uv) if need_h: return (x,y,uh) return (x,y) # start and target predicate start = make_state(Sx, Sy, False, False) if need_v and need_h: def is_target(st): return st[0]==Gx and st[1]==Gy and st[2] and st[3] elif need_v: def is_target(st): return st[0]==Gx and st[1]==Gy and st[2] elif need_h: def is_target(st): return st[0]==Gx and st[1]==Gy and st[2] else: def is_target(st): return st[0]==Gx and st[1]==Gy dq = deque([start]) visited = {start} parent = {start: None} move_from = {} while dq: st = dq.popleft() # unpack x,y,uv,uh properly x,y = st[0], st[1] idx = 2 if need_v: uv = st[idx] idx += 1 else: uv = False if need_h: uh = st[idx] else: uh = False if is_target(st): # reconstruct path path = [] cur = st while parent[cur] is not None: path.append(move_from[cur]) cur = parent[cur] path.reverse() # count moves A0 = sum(1 for dx,dy in path if dx==1 and dy==0) B0 = sum(1 for dx,dy in path if dx==-1 and dy==0) C0 = sum(1 for dx,dy in path if dx==0 and dy==1) D0 = sum(1 for dx,dy in path if dx==0 and dy==-1) return A0, B0, C0, D0, len(path) # expand neighbors for dx,dy in DIRS: nx,ny = x+dx, y+dy if not (0<=nx 0 can_horz = (C0 + D0) > 0 x = find_shift(A0, B0, can_vert, is_prime, LIMIT) if x is None: continue y = find_shift(C0, D0, can_horz, is_prime, LIMIT) if y is None: continue total = base_len + 2*(x + y) if total < best: best = total print(best if best < float('inf') else -1) if __name__ == "__main__": solve()