#include using namespace std; #define rep(i,n) for(int (i) = 0 ; (i) < (int)(n) ; (i)++) #define REP(i,a,b) for(int (i) = a ; (int)(i) <= (int)(b) ; (i)++) #define all(n) (n).begin(),(n).end() typedef vector Vi; typedef vector VVi; typedef pair Pii; typedef vector VPii; int done[100][100][1802]; int L[100][100]; int dx[] = {-1,0,1,0}; int dy[] = {0,-1,0,1}; struct NODE{ int x,y,c,h; }; bool operator < (const NODE &a,const NODE &b){ return a.h < b.h; } int main(){ int N,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]; rep(i,100)rep(j,100)rep(k,1802) done[i][j][k] = -1e9; priority_queue Q; Q.push({Sx,Sy,0,V}); done[Sy][Sx][0] = V; unsigned int ans = -1; while( Q.size() ){ auto q = Q.top(); Q.pop(); if( q.h <= 0 ) continue; if( q.c > 1800 ) continue; if( done[q.y][q.x][q.c] != q.h ) continue; if( q.y == Gy && q.x == Gx ){ ans = min(ans,(unsigned)q.c); continue; } rep(i,4){ int tx = q.x + dx[i]; int ty = q.y + dy[i]; if( tx < 0 || ty < 0 || ty >= N || tx >= N ) continue; if( done[ty][tx][q.c+1] < q.h-L[ty][tx] ){ done[ty][tx][q.c+1] = q.h-L[ty][tx]; Q.push({tx,ty,q.c+1,q.h-L[ty][tx]}); } } } cout << (int) ans << endl; }