#include #define REP(i, x, n) for(int i = x; i < (int)(n); i++) #define rep(i, n) REP(i, 0, n) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define F first #define S second #define mp make_pair using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair P; const int dx[] = {1, -1, 0, 0}; const int dy[] = {0, 0, 1, -1}; struct State { int x, y, damage; State(int x, int y, int d): x(x), y(y), damage(d) {} }; int N, V, SX, SY, GX, GY; int L[100][100]; int minCost[100][100][2000]; int solve() { SX--; SY--; GX--; GY--; V = min(2000, V); rep(i, N) rep(j, N) rep(k, V) minCost[i][j][k] = 1 << 29; queue Q; Q.push(State(SX, SY, 0)); minCost[SY][SX][0] = 0; while(!Q.empty()) { State stt = Q.front(); Q.pop(); if(stt.x == GX && stt.y == GY) { return minCost[stt.y][stt.x][stt.damage]; } rep(i, 4) { int nx = dx[i] + stt.x; int ny = dy[i] + stt.y; if(!(0 <= nx && nx < N && 0 <= ny && ny < N)) continue; if(stt.damage + L[ny][nx] >= V) continue; if(minCost[ny][nx][stt.damage + L[ny][nx]] <= minCost[stt.y][stt.x][stt.damage] + 1) continue; minCost[ny][nx][stt.damage + L[ny][nx]] = minCost[stt.y][stt.x][stt.damage] + 1; Q.push(State(nx, ny, stt.damage + L[ny][nx])); } } return -1; } int main() { // ios_base::sync_with_stdio(false); cin >> N >> V >> SX >> SY >> GX >> GY; rep(i, N) rep(j, N) cin >> L[i][j]; cout << solve() << endl; return 0; }