#include #include #include #include #include #define mp std::make_pair typedef std::pair P; const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1}; int N, V, SX, SY, GX, GY; int map[101][101]; int d[101][101][10001]; int main(){ scanf("%d %d %d %d %d %d", &N, &V, &SX, &SY, &GX, &GY); for(int i=1;i<=N;i++){ for(int j=1;j<=N;j++){ scanf("%d", &map[i][j]); } } std::fill(&d[0][0][0], &d[0][0][0]+101*101*10001, 1001001001); std::priority_queue, std::greater

> q; q.push(mp(0, SY+101*(SX+101*V))); d[SY][SX][V] = 0; int res = -1; while(!q.empty()){ P p = q.top(); q.pop(); int t = p.first, x = p.second / 101 % 101, y = p.second % 101, l = p.second / (101*101); if(x == GX && y == GY){res = t; break;} for(int i=0;i<4;i++){ int nx = x + dx[i], ny = y + dy[i]; if(1 <= nx && nx <= N && 1 <= ny && ny <= N && l - map[ny][nx] > 0 && t+1 < d[ny][nx][l-map[ny][nx]]){ int nl = l-map[ny][nx]; d[ny][nx][nl] = t+1; q.push(mp(d[ny][nx][nl], ny+101*(nx+101*nl))); } } } printf("%d\n", res); }