#include #define REP(i, n) for (int i = 0; i < (int)(n); i++) #define REPR(i, n) for(int i = (int)(n); i >= 0; i--) #define FOR(i, s, n) for (int i = (s); i < (int)(n); i++) #define ALL(v) v.begin(), v.end() using namespace std; typedef long long ll; ll N, K, W, H, M, C, V; const int MAX = 510000; const int MOD = 1000000007; long long fac[MAX], finv[MAX], inv[MAX]; vector cx, cy, c; ll MM = 1e12; void COMinit() { fac[0] = fac[1] = 1; finv[0] = finv[1] = 1; inv[1] = 1; for (int i = 2; i < MAX; i++){ fac[i] = fac[i - 1] * i % MOD; inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD; finv[i] = finv[i - 1] * inv[i] % MOD; } } long long COM(int n, int k){ if (n < k) return 0; if (n < 0 || k < 0) return 0; return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD; } std::vector Eratosthenes(int n ){ std::vector is_prime( n + 1 ); for( int i = 0; i <= n; i++ ) is_prime[ i ] = true; std::vector P; for( int i = 2; i <= n; i++ ){ if( is_prime[ i ] ){ for( int j = 2 * i; j <= n; j += i ){ is_prime[ j ] = false; } P.emplace_back( i ); } } return P; } vector> edge(tuple u){ vector> ret; int i = get<0>(u), j = get<1>(u); if(i > 0) {ret.push_back(make_pair(i-1, j));} if(j > 0) {ret.push_back(make_pair(i, j-1));} if(i < N-1) {ret.push_back(make_pair(i + 1, j));} if(j < N-1) {ret.push_back(make_pair(i , j + 1));} return ret; } int main(){ cin >> N >> V; int initx, inity, finx, finy; cin >> inity >> initx >> finy >> finx; --initx; --inity; --finx; --finy; vector> dam(N, vector (N)); REP(i,N) REP(j,N) cin >>dam[i][j]; //bfs queue> q; q.push(make_tuple(initx, inity, V)); ll dp[N][N][V+1]; dp[initx][inity][V] =0; while(!q.empty()){ auto v = q.front(); q.pop(); for(auto u : edge(v)){ ll nv = get<2>(v) - dam[u.first][u.second]; if(nv <= 0) continue; if(dp[u.first][u.second][nv] >= 0) continue; dp[u.first][u.second][nv] = dp[get<0>(v)][get<1>(v)][get<2>(v)] + 1 ; if(u.first == finx and u.second == finy) { cout << dp[u.first][u.second][nv] << "\n"; return 0; } q.push(make_tuple( u.first, u.second, nv )); } } cout << -1 << "\n"; return 0; }