#include using namespace std; using ll = long long; using vi = vector; using vb = vector; using vd = vector; using vl = vector; using vvi = vector; using vvb = vector; using vvd = vector; using vvl = vector; #define REP(i,n) for(ll i=0; i<(n); ++i) int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; bool contain(ll n, ll x) { return 0 <= x && x < n; } int main() { ll n, v, sx, sy, gx, gy; cin >> n >> v >> sx >> sy >> gx >> gy; sx--; sy--; gx--; gy--; vvi field(n, vi(n)); REP(y, n) REP(x, n) cin >> field[y][x]; vvl vital(n, vl(n, 0)); using P = pair>>; priority_queue, greater

> que; que.push({0, {v, {sx, sy}}}); while (!que.empty()) { auto _ = que.top(); que.pop(); ll times = _.first; ll cur_v = _.second.first; auto pos = _.second.second; if (pos.first == gx && pos.second == gy) { cout << times << endl; return 0; } if (vital[pos.second][pos.first] >= cur_v) continue; vital[pos.second][pos.first] = cur_v; REP(i, 4) { auto n_pos = make_pair(pos.first + dx[i], pos.second + dy[i]); if (!contain(n, n_pos.first) || !contain(n, n_pos.second)) continue; ll n_v = cur_v - field[n_pos.second][n_pos.first]; if(n_v > vital[n_pos.second][n_pos.first]) que.push({ times + 1, { n_v, n_pos } }); } } cout << -1 << endl; return 0; }