#include #include #include using namespace std; struct State { int x, y, times, hp; }; const int kMAX_N = 110; int L[kMAX_N][kMAX_N]; int max_hp[kMAX_N][kMAX_N]; int N, V, sx, sy, gx, gy; int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; void Solve() { queue que; max_hp[sx - 1][sy - 1] = V; que.push((State){sx - 1, sy - 1, 0, V}); while (!que.empty()) { State s = que.front(); que.pop(); if (s.x == gx - 1 && s.y == gy - 1) { cout << s.times << endl; return; } for (int i = 0; i < 4; i++) { int nx = s.x + dx[i], ny = s.y + dy[i]; if (0 <= nx && nx < N && 0 <= ny && ny < N && s.hp - L[nx][ny] > max_hp[nx][ny]) { max_hp[nx][ny] = s.hp - L[nx][ny]; que.push((State){nx, ny, s.times + 1, s.hp - L[nx][ny]}); } } } cout << -1 << endl; } int main() { cin >> N >> V >> sx >> sy >> gx >> gy; for (int y = 0; y < N; y++) { for (int x = 0; x < N; x++) { cin >> L[x][y]; } } Solve(); return 0; }