#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _MSC_VER #include #endif #define FOR(i, a, b) for(int i = (a); i < (int)(b); ++i) #define rep(i, n) FOR(i, 0, n) #define ALL(v) v.begin(), v.end() #define REV(v) v.rbegin(), v.rend() #define MEMSET(v, s) memset(v, s, sizeof(v)) #define UNIQUE(v) (v).erase(unique(ALL(v)), (v).end()) #define MP make_pair #define MT make_tuple using namespace std; typedef long long ll; typedef long double ld; typedef pair P; const int N = 101; int dist[2000][N][N]; struct state{ int x, y, h, d; bool operator < (const state &rhs) const{ return d > rhs.d; } }; int field[111][111]; int& dist_ref(state &st){ return dist[st.h][st.x][st.y]; }; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int main(){ cin.tie(0); ios::sync_with_stdio(false); cout.setf(ios::fixed); cout.precision(20); int n, v, sx, sy, gx, gy; cin >> n >> v >> sx >> sy >> gx >> gy; --sx, --sy, --gx, --gy; if (v >= 2000){ cout << abs(gx - sx) + abs(sy - gy) << endl; return 0; } rep(i, n) rep(j, n) cin >> field[i][j]; state st = { sx, sy, v, 0 }; priority_queue q; rep(i, v + 1) rep(j, n) rep(k, n) dist[i][j][k] = 1e9; dist_ref(st) = 1; q.push(st); while (!q.empty()){ auto st = q.top(); q.pop(); if (dist_ref(st) < st.d) continue; if (st.x == gx && st.y == gy){ cout << st.d << endl; return 0; } rep(i, 4){ int nx = st.x + dx[i], ny = st.y + dy[i]; if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue; int nh = st.h - field[ny][nx]; if (nh <= 0) continue; state nxt = { nx, ny, nh, st.d + 1 }; int &d = dist_ref(nxt); if (d <= nxt.d) continue; d = nxt.d; q.push(nxt); } } cout << -1 << endl; }