#include #define show(x) cout << #x << " = " << x << endl using namespace std; using ll = long long; using pii = pair; template ostream& operator<<(ostream& os, const vector& v) { os << "sz=" << v.size() << "\n["; for (const auto& p : v) { os << p << ","; } os << "]\n"; return os; } template ostream& operator<<(ostream& os, const pair& p) { os << "(" << p.first << "," << p.second << ")"; return os; } constexpr ll MOD = 1e9 + 7; template constexpr T INF = numeric_limits::max() / 100; constexpr int dir[5] = {0, 1, 0, -1, 0}; constexpr int MAX = 100; int N, V; int field[MAX][MAX]; int checked[MAX][MAX]; int s, g; int encode(int x, int y) { return x * N + y; } pii decode(int code) { return make_pair(code / N, code % N); } struct Info { Info() = default; Info(int p, int d, int h) : pos{p}, day{d}, hp{h} {} int pos; int day; int hp; void print() const { cout << "pos: " << pos << "\nday: " << day << "\nhp: " << hp << endl; } }; int solve() { queue q; q.push(Info{s, 0, V}); while (not q.empty()) { const auto p = q.front(); q.pop(); if (g == p.pos) { return p.day; } const pii pos = decode(p.pos); const int x = pos.first; const int y = pos.second; const int d = p.day; const int hp = p.hp; for (int di = 0; di < 4; di++) { const int newx = x + dir[di]; const int newy = y + dir[di + 1]; if (0 <= newx and newx < N and 0 <= newy and newy < N) { if (hp > field[newx][newy] and checked[newx][newy] < hp - field[newx][newy]) { checked[newx][newy] = hp - field[newx][newy]; q.push(Info{encode(newx, newy), d + 1, hp - field[newx][newy]}); } } } } return -1; } int main() { cin >> N >> V; int sx, sy, gx, gy; cin >> sx >> sy >> gx >> gy; sx--, sy--, gx--, gy--; s = encode(sx, sy); g = encode(gx, gy); for (ll y = 0; y < N; y++) { for (ll x = 0; x < N; x++) { cin >> field[x][y]; checked[x][y] = -1; } } cout << solve() << endl; return 0; }