#include using namespace std; #define REP(i,a,b) for(int i=a;i rhs.cost; return hp < rhs.hp; } }; int const dx[4] = {-1,0,1,0}; int const dy[4] = {0,-1,0,1}; int const INF = 1<<29; int N; bool valid(int x, int y) { return 0<=x && x cdist[110][110]; int main () { int V, sx, sy, gx, gy; cin >> N >> V >> sx >> sy >> gx >> gy; sx --, sy --, gx --, gy --; rep(i, N) { rep(j, N) { cin >> L[i][j]; } } priority_queue pq; pq.push((State){V, 0, sx, sy}); ll ans = INF; while(!pq.empty()) { int hp = pq.top().hp; ll cost = pq.top().cost; int x = pq.top().x, y = pq.top().y; pq.pop(); if(gx == x && gy == y) { ans = min(ans, cost); continue; } rep(i, 4) { int nx = x+dx[i], ny = y+dy[i]; if(!valid(nx, ny)) continue; int nhp = hp-L[ny][nx]; if(nhp <= 0) { continue; } if(cdist[ny][nx].find(nhp) != cdist[ny][nx].end() && cdist[ny][nx][nhp] <= cost+1) { continue; } cdist[ny][nx][nhp] = cost+1; pq.push((State){nhp, cdist[ny][nx][nhp], nx, ny}); } } if(ans != INF) cout << ans << endl; else cout << -1 << endl; return 0; }