#include using namespace std; typedef long long int ll; typedef pair pii; typedef vector vi; typedef vector > vii; #define rrep(i, m, n) for(int (i)=(m); (i)<(n); (i)++) #define erep(i, m, n) for(int (i)=(m); (i)<=(n); (i)++) #define rep(i, n) for(int (i)=0; (i)<(n); (i)++) #define rev(i, n) for(int (i)=(n)-1; (i)>=0; (i)--) #define vrep(i, c) for(__typeof((c).begin())i=(c).begin(); i!=(c).end(); i++) #define ALL(v) (v).begin(), (v).end() #define mp make_pair #define pb push_back template inline void minup(T1& m, T2 x){ if(m>x) m=static_cast(x); } template inline void maxup(T1& m, T2 x){ if(m(x); } #define INF 1000000000 #define MOD 1000000007 #define EPS 1E-12 const int MAX_N = 100; const int dx[] = {-1, 0, 1, 0}; const int dy[] = {0, -1, 0, 1}; int N, V; int sx, sy; int gx, gy; int L[MAX_N][MAX_N]; int dp[MAX_N][MAX_N]; inline bool check(int hx, int hy){ return 0<=hx&&hx> N >> V; cin >> sx >> sy; sx -= 1; sy -= 1; swap(sx, sy); cin >> gx >> gy; gx -= 1; gy -= 1; swap(gx, gy); rep(i, N) rep(j, N) cin >> L[i][j]; rep(i, N) rep(j, N) dp[i][j] = INF; queue > que; que.push(mp(mp(sx, sy), 0)); dp[sx][sy] = 0; while(!que.empty()){ pair top = que.front(); que.pop(); pii here = top.first; int v = top.second; int hx = here.first; int hy = here.second; if(hx == gx && hy == gy){ cout << v << endl; return 0; } rep(k, 4){ int nx = hx + dx[k]; int ny = hy + dy[k]; if(!check(nx, ny)) continue; if(dp[nx][ny] > dp[hx][hy] + L[nx][ny] && dp[hx][hy] + L[nx][ny] < V){ que.push(mp(mp(nx, ny), v + 1)); dp[nx][ny] = dp[hx][hy] + L[nx][ny]; } } } cout << -1 << endl; return 0; }