#include #define rep(i,n) for (int i = 0; i < (n); ++i) #define rrep(i,n) for (int i = (n)-1; i>=0; --i) #define chmax(a, b) a = max(a, b) #define chmin(a, b) a = min(a, b) #define all(x) (x).begin(), (x).end() using namespace std; using ll = long long; using P = pair; using VI = vector; using VVI = vector; int dist[100][100][2000]; int l[100][100]; const int INF = 10000; const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; struct cmp { bool operator()(tuple &x, tuple &y) { return get<0>(x) > get<0>(y); } }; int main() { int n, v, sx, sy, gx, gy; scanf("%d%d%d%d%d%d", &n, &v, &sy, &sx, &gy, &gx); --sx; --sy; --gx; --gy; rep(i, n) rep(j, n) scanf("%d", &l[i][j]); int shortest_dist = abs(sx - gx) + abs(sy - gy); if (v > shortest_dist * 9) { printf("%d\n", shortest_dist); return 0; } rrep(i, n)rrep(j, n)rrep(k, v + 1) dist[i][j][k] = INF; priority_queue,vector>,cmp> q; dist[sx][sy][v] = 0; q.emplace(0, sx, sy, v); while(!q.empty()) { int d, x, y, vit; tie(d, x, y, vit) = q.top(); q.pop(); if (d > dist[x][y][vit]) continue; rrep(k, 4) { int nx = x + dx[k], ny = y + dy[k]; if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue; int nvit = vit - l[nx][ny]; int nd = d + 1; if (nvit > 0 && nd < dist[nx][ny][nvit]) { dist[nx][ny][nvit] = nd; q.emplace(nd, nx, ny, nvit); } } } int ans = INF; rrep(k, v + 1) chmin(ans, dist[gx][gy][k]); if (ans == INF) ans = -1; printf("%d\n", ans); }