#include #include #include using namespace std; constexpr int8_t DX[4] = {0, 1, 0, -1}, DY[4] = {1, 0, -1, 0}; int8_t N, sx, sy, gx, gy, L[100][100]; int16_t V, d[100][100]; int main(void) { ios::sync_with_stdio(false); scanf("%hhd %hd %hhd %hhd %hhd %hhd", &N, &V, &sx, &sy, &gx, &gy); --sx, --sy, --gx, --gy; for(int8_t i = 0; i < N; ++i) for(int8_t j = 0; j < N; ++j) scanf("%hhd", &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) { printf("%d", dist); return 0; } for(int8_t dir = 0; dir < 4; ++dir) { int8_t nx = x + DX[dir], ny = y + DY[dir]; if(!(0 <= nx and nx < N and 0 <= ny and ny < N)) continue; int16_t nc = c - L[ny][nx]; if(d[nx][ny] < nc) { d[nx][ny] = nc; que.push(make_tuple(dist + 1, nx, ny, nc)); } } } printf("-1\n"); return 0; }