// #pragma GCC target("avx2") // #pragma GCC optimize("O3") // #pragma GCC optimize("unroll-loops") #include // #include using namespace std; // using namespace atcoder; #define rep(i,m,n,k) for (int i = (int)(m); i < (int)(n); i += (int)(k)) #define rrep(i,m,n,k) for (int i = (int)(m); i > (int)(n); i += (int)(k)) #define all(x) x.begin(),x.end() #define ll long long #define list(T,A,N) vector A(N);for(int i=0;i<(int)(N);i++){cin >> A[i];} template inline bool chmin(T& a, T b){if(a > b){a = b; return true;} return false;} template inline bool chmax(T& a, T b){if(a < b){a = b; return true;} return false;} // #define int long long int main(){ ios::sync_with_stdio(false); std::cin.tie(nullptr); int N,V,sx,sy,gx,gy; cin >> N >> V >> sx >> sy >> gx >> gy; vector> L(N,vector (N)); rep(i,0,N,1){ rep(j,0,N,1){ cin >> L[j][i]; } } vector> dxy = {{-1,0},{1,0},{0,1},{0,-1}}; vector val(200000000); sx -=1; sy -=1; gx -=1; gy -=1; int N2 = N*N; val[sx+N*sy+N2*V] = 1; queue v; v.push(sx+N*sy+N2*V); while(!v.empty()){ auto xym = v.front(); v.pop(); auto m = xym/N2; auto y = xym%N2/N; auto x = xym%N; for(auto [dx,dy]:dxy){ if((x+dx>=N)||(y+dy>=N)||(x+dx<0)||(y+dy<0)) continue; if(m-L[x+dx][y+dy]<=0) continue; if(val[x+dx+N*(y+dy)+(m-L[x+dx][y+dy])*N2]!=0) continue; if((x+dx==gx)&&(y+dy==gy)){ cout << val[xym] << endl; return 0; } val[x+dx+N*(y+dy)+(m-L[x+dx][y+dy])*N2] = val[xym]+1; v.push(x+dx+N*(y+dy)+(m-L[x+dx][y+dy])*N2); } } cout << -1 << endl; return 0; }