#include #include #include #include #include #include #include using namespace std; vector> g; int N, V, SX, SY, GX, GY; int vxfs(int nv){ int dx[] = { 0, 1, 0, -1 }, dy[] = { 1, 0, -1, 0 }; int ct=0; queue< array > que; que.push({ SY, SX, nv, 0 }); vector>> usd(N, vector>(N,{0,99999})); map, int> mp; mp[{SY,SX,0}]=nv; while(!que.empty()){ auto c = que.front(); int cy = c[0], cx = c[1], cv=c[2], cc = c[3]; que.pop(); if(cy == GY && cx == GX){ //printf("mp=%d:ct=%d\n",mp.size(),ct); return cc; } for(int i=0;i<4;++i){ ct++; int ny = cy + dy[i], nx = cx + dx[i]; if(ny<0 || ny >= N || nx<0 || nx >= N) continue; int ne = cv - g[ny][nx]; if(ne < 1) continue; if(mp[{ny,nx, cc+1}] >= ne) continue; if( usd[ny][nx][0] < ne || usd[ny][nx][1] > cc+1){ usd[ny][nx] = {ne, cc+1}; mp[{ny,nx,cc+1}] = ne; que.push({ ny, nx, ne, cc + 1 }); } } } //printf("mp=%d:ct=%d\n",mp.size(),ct); return -1; } int main() { cin >> N >> V >> SX >> SY >> GX >> GY; SX--; SY--; GX--; GY--; g.assign(N, vector(N)); for(int i=0;i> g[i][j]; cout << vxfs(V) << endl; return 0; }