#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; using vi = vector; using vvi = vector; using vl = vector; using vvl = vector; using vb = vector; using vvb = vector; using vd = vector; using vs = vector; using pii = pair; using pll = pair; using pdd = pair; using vpii = vector; using vpll = vector; using vpdd = vector; const int inf = (1 << 30) - 1; const ll INF = 1LL << 60; const int MOD = 1000000007; const int dy[4] = { -1,0,1,0 }; const int dx[4] = { 0,1,0,-1 }; int main() { int n, V, sx, sy, gx, gy; cin >> n >> V >> sx >> sy >> gx >> gy; sx--; sy--; gx--; gy--; vvi g(n, vi(n)); int h = n, w = n; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { cin >> g[y][x]; } } vector dist(n, vvi(n, vi(V + 1, inf))); dist[sy][sx][0] = 0; queue> que; que.push({ {sy, sx} , 0 }); while (!que.empty()) { pair p = que.front(); que.pop(); auto [y, x] = p.first; int v = p.second; int d = dist[y][x][v]; if (y == gy && x == gx) { cout << d << endl; return 0; } for (int i = 0; i < 4; i++) { int y2 = y + dy[i]; int x2 = x + dx[i]; if (y2 < 0 || y2 > h - 1 || x2 < 0 || x2 > w - 1) continue; int c = g[y2][x2]; if (v + c >= V) continue; if (dist[y2][x2][v + c] <= d + 1) continue; dist[y2][x2][v + c] = d + 1; que.push({ {y2, x2}, v + c }); } } cout << -1 << endl; return 0; }