#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; bool 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]; priority_queue Q; Q.push({Sx,Sy,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] ) continue; else done[q.y][q.x][q.c] = true; if( q.y == Gy && q.x == Gx ){ ans = min(ans,(unsigned)q.c); continue; } for(int i = 0 ; i < 4 ; i++){ int tx = q.x + dx[i]; int ty = q.y + dy[i]; if( tx < 0 || ty < 0 || ty >= N || tx >= N ) continue; Q.push({tx,ty,q.c+1,q.h-L[ty][tx]}); } } cout << (int) ans << endl; }