#include #include #include #include #include #include using namespace std; struct state { int x, y, t, v; }; int main() { int n, v, sx, sy, gx, gy; cin >> n >> v >> sx >> sy >> gx >> gy; vector< vector > land(n+2, vector(n+2, 1e8)); vector< vector > maxv(n+2, vector(n+2, 0)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> land[i][j]; } } const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; int nx, ny, nv; int ans = -1; queue que; state st = {sx, sy, 0, v}; que.push(st); maxv[sy][sx] = v; while(!que.empty()) { st = que.front(); que.pop(); if (st.x == gx && st.y == gy) { ans = st.t; break; } for (int i = 0; i < 4; i++) { nx = st.x + dx[i]; ny = st.y + dy[i]; nv = st.v - land[ny][nx]; if (land[ny][nx] < st.v && maxv[ny][nx] < nv) { maxv[ny][nx] = nv; que.push((state) {nx, ny, st.t + 1, nv} ); } } } cout << ans << endl; return 0; }