#include #include #include #include #include #include #include #include #include using namespace std; using ll = long long; template inline bool chmax(T& a, T b){ if (a < b){ a = b; return true; } return false; } template inline bool chmin(T& a, T b){ if (a > b){ a = b; return true; } return false; } int dist[102][102][10004]; int A[102][102]; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1}; int main() { int n, v, sx, sy, gx, gy; cin >> n >> v >> sy >> sx >> gy >> gx; sx--; sy--; gx--; gy--; for(int i=0; i> A[i][j]; for(int i=0; i que; que.push_back(nsq*v + sx*n + sy); while (!que.empty()) { int vxy, tx, ty, tv; vxy = que.front(); que.pop_front(); tv = vxy/nsq; tx = (vxy%nsq)/n; ty = (vxy%nsq)%n; if (tx==gx && ty==gy) { cout << dist[tx][ty][tv] << endl; return 0; } for(int i=0; i<4; ++i) { int nx, ny, nv; nx = tx + dx[i]; ny = ty + dy[i]; if (0 <= nx && nx < n && 0 <= ny && ny < n && tv - A[nx][ny] > 0) { nv = tv - A[nx][ny]; if (dist[nx][ny][nv] == -1) { dist[nx][ny][nv] = dist[tx][ty][tv] + 1; que.push_back(nsq*nv + nx*n + ny); } } } } cout << -1 << endl; return 0; }