from collections import deque import sys def main(): input = sys.stdin.read().split() idx = 0 N = int(input[idx]); idx +=1 V = int(input[idx]); idx +=1 SX = int(input[idx]); idx +=1 SY = int(input[idx]); idx +=1 GX = int(input[idx]); idx +=1 GY = int(input[idx]); idx +=1 L = [] for _ in range(N): row = list(map(int, input[idx:idx+N])) idx += N L.append(row) max_v = [[-1]*(N+2) for _ in range(N+2)] directions = [ (-1,0), (1,0), (0,-1), (0,1) ] # Left, Right, Up, Down q = deque() q.append( (SX, SY, V, 0) ) max_v[SX][SY] = V while q: x, y, v, steps = q.popleft() for dx, dy in directions: nx = x + dx ny = y + dy if 1 <= nx <= N and 1 <= ny <= N: # Calculate new v L_val = L[ny-1][nx-1] new_v = v - L_val if new_v <= 0: continue # Not allowed as it leads to immediate death # Check if it's the goal if nx == GX and ny == GY: print(steps + 1) return else: # Update max_v and enqueue if better state if new_v > max_v[nx][ny]: max_v[nx][ny] = new_v q.append( (nx, ny, new_v, steps + 1) ) print(-1) if __name__ == '__main__': main()