#include #include #include #include #include #include #include #include using namespace std; #define REP(i,a,b) for(int i=a;i<(int)b;i++) #define rep(i,n) REP(i,0,n) typedef long long ll; int N, V; int sx, sy, gx, gy; int dp[2][101][101]; int L[101][101]; int dx[4] = {-1,0,1,0}; int dy[4] = {0,-1,0,1}; constexpr auto inrange(int x, int y) { return 0<=x&&x constexpr auto chmax(T& x, T a) { x = max(x, a); } int main() { cin >> N >> V >> sx >> sy >> gx >> gy; --sx, --sy, --gx, --gy; rep(i, N) rep(j, N) { cin >> L[i][j]; } int constexpr MaxStep = 11111; dp[0][sy][sx] = V; rep(step, MaxStep) { auto curr = dp[step&1], next = dp[(step+1)&1]; if(curr[gy][gx] > 0) { cout << step << endl; return 0; } rep(y, N) rep(x, N) { next[y][x] = 0; } rep(y, N) rep(x, N) { rep(k, 4) { int nx = x+dx[k], ny = y+dy[k]; if(!inrange(nx, ny)) { continue; } if(curr[y][x] <= L[ny][nx]) { continue; } chmax(next[ny][nx], curr[y][x] - L[ny][nx]); } } } cout << -1 << endl; return 0; }