#include using namespace std; #define ll long long const int INF = 1E9; int arr[2<<6][2<<6]; const static int dirs[] = {0, 1, 0, -1, 0}; int main(){ cin.tie(nullptr)->sync_with_stdio(false); int N, V, Sx, Sy, Gx, Gy; cin >> N >> V >> Sx >> Sy >> Gx >> Gy; --Sx, --Sy; --Gx; --Gy; for(int i = 0; i < N; ++i){ for(int j = 0; j < N; ++j){ cin >> arr[i][j]; } } vector dist(N, vector>(N)); queue> q; q.emplace(Sx, Sy, V, 0); dist[Sx][Sy][V]=0; while(!q.empty()){ auto [x, y, v, d] = q.front(); q.pop(); for(int k = 0; k < 4; ++k){ const int nx = x + dirs[k]; const int ny = y + dirs[k + 1]; if(nx < 0 || ny < 0 || nx >= N || ny >= N) continue; int v2 = v - arr[ny][nx]; if(v2 <= 0) continue; if(!dist[nx][ny].empty() && dist[nx][ny].rbegin()->first >= v2) continue; dist[nx][ny][v2] = d + 1; q.emplace(nx, ny, v2, d + 1); } } int ret = INF; for(auto& [k, v]: dist[Gx][Gy]){ ret = min(ret, v); } if(ret == INF) ret = -1; cout << ret << endl; return 0; }