#include #define rep(i, a) for (int i = 0; i < (a); i++) #define rep2(i, a, b) for (int i = (a); i < (b); i++) #define repr(i, a) for (int i = (a) - 1; i >= 0; i--) #define repr2(i, a, b) for (int i = (b) - 1; i >= (a); i--) using namespace std; typedef long long ll; const ll inf = 1e9; const ll mod = 1e9 + 7; short dp[100][100][10000]; // y, x, damage => dist typedef tuple P; // dist, damage, y, x int N, V, sy, sx, gy, gx, L[100][100]; int main() { cin >> N >> V >> sy >> sx >> gy >> gx; sy--; sx--; gy--; gx--; rep (j, N) rep (i, N) cin >> L[i][j]; priority_queue, greater

> q; q.emplace(0, 0, sy, sx); rep (i, 100) rep (j, 100) rep (k, 10000) dp[i][j][k] = 10101; dp[sy][sx][0] = 0; while (!q.empty()) { P p = q.top(); q.pop(); int dist = get<0>(p); int damage = get<1>(p); int y = get<2>(p); int x = get<3>(p); if (y == gy && x == gx) break; if (dp[y][x][damage] < dist) continue; int dy[] = {0, 1, 0, -1}; int dx[] = {1, 0, -1, 0}; rep (k, 4) { int ny = y + dy[k]; int nx = x + dx[k]; if (ny < 0 || ny >= N || nx < 0 || nx >= N) continue; if (damage + L[ny][nx] >= V) continue; if (dp[ny][nx][damage + L[ny][nx]] > dp[y][x][damage] + 1) { dp[ny][nx][damage + L[ny][nx]] = dp[y][x][damage] + 1; q.emplace(dp[ny][nx][damage + L[ny][nx]], damage + L[ny][nx], ny, nx); } } } int ans = inf; rep (k, V) { ans = min(ans, (int)dp[gy][gx][k]); } if (ans == 10101) { cout << -1 << endl; } else { cout << ans << endl; } return 0; }