#include using namespace std; #define REP(i,n) for(ll i=0; i<(ll)(n); i++) #define FOR(i,n,m) for (ll i=n; i<(ll)(m); i++) #define pb push_back #define INF 1000000007 #define all(a) (a).begin(),(a).end() #define per(b) #define MAX_N 102 #define MAX_V 1785 typedef long long ll; typedef pair p; typedef pair pv; int dy[4]={-1,1,0,0}; int dx[4]={0,0,1,-1}; int N,V,Sx,Sy,Gx,Gy; int L[MAX_N][MAX_N]; bool canProceed(int y, int x) {return 0<=x&&x q; d[y][x][v]=0; q.push(pv(p(y,x),v)); while(!q.empty()){ pv tmp = q.front();q.pop(); y=tmp.first.first;x=tmp.first.second;v=tmp.second; REP(i,4){ int ny=y+dy[i],nx=x+dx[i]; if(!canProceed(ny, nx)) continue; int nv=v-L[ny][nx]; if(nv<=0) continue; if(d[ny][nx][nv]) continue; if(ny==Gy&&nx==Gx){ cout << d[y][x][v]+1 << endl; return; } d[ny][nx][nv] = d[y][x][v] + 1; q.push(pv(p(ny,nx),nv)); } } cout << -1 << endl; return; } int main(){ ios::sync_with_stdio(false); cin >> N >> V >> Sx >> Sy >> Gx >> Gy; V=min(V,MAX_V-1); Sx--;Sy--;Gx--;Gy--; REP(i,N)REP(j,N) cin >> L[i][j]; bfs(Sy,Sx,V); return 0; }