#include using namespace std; typedef pair P; typedef pair> PP; typedef long long ll; const double EPS = 1e-8; const int INF = 1e9; const int MOD = 1e9+7; int dy[] = {0,1,0,-1}; int dx[] = {1,0,-1,0}; int bfs(vector> L,int sx,int sy,int gx,int gy,int V,vector>>& used){ queue qx,qy,qv,qt; qx.push(sx);qy.push(sy);qv.push(V);qt.push(0); int ret = INF; while(!qx.empty()){ int x,y,v,t; x = qx.front();qx.pop(); y = qy.front();qy.pop(); v = qv.front();qv.pop(); t = qt.front();qt.pop(); if(gy == y && gx == x){ ret = min(ret,t); continue; } for(int i=0;i<4;i++){ int nx = x + dx[i],ny = y + dy[i]; if(nx < 0 || ny < 0 || nx >= L[0].size() || ny >= L.size())continue; int nv = v - L[ny][nx]; if(nv <= 0 || used[ny][nx][nv])continue; used[ny][nx][nv] = true; qx.push(nx); qy.push(ny); qv.push(nv); qt.push(t + 1); } //cerr << y << " " << x << " " << v << endl; } return ret; } int main(void) { int n,v,sx,sy,gx,gy; cin >> n >> v >> sx >> sy >> gx >> gy; vector> L(n,vector(n)); for(int i=0;i> L[i][j]; } } sy--;sx--;gy--;gx--; vector>> used(n,vector>(n,vector(v+1,false))); int ret = bfs(L,sx,sy,gx,gy,v,used); cout << (ret>=INF ? -1 : ret) << endl; return 0; }