#include #include using namespace std; constexpr int DX[4] = {0, 1, 0, -1}, DY[4] = {1, 0, -1, 0}; int N, V, sx, sy, gx, gy; int L[100][100], d[100][100]; int main(void) { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int N, V, sx, sy, gx, gy; cin >> N >> V >> sx >> sy >> gx >> gy; --sx, --sy, --gx, --gy; for(int i = 0; i < N; ++i) for(int j = 0; j < N; ++j) cin >> L[i][j]; queue> que; d[sx][sy] = V; que.push(make_tuple(0, sx, sy, V)); while(!que.empty()) { auto [dist, x, y, c] = que.front(); que.pop(); if(x == gx and y == gy) { cout << dist << "\n"; return 0; } for(int dir = 0; dir < 4; ++dir) { int nx = x + DX[dir], ny = y + DY[dir]; if(!(0 <= nx and nx < N and 0 <= ny and ny < N)) continue; int nc = c - L[ny][nx]; if(d[nx][ny] < nc) { d[nx][ny] = nc; que.push(make_tuple(dist + 1, nx, ny, nc)); } } } cout << -1 << "\n"; return 0; }