#include "bits/stdc++.h" using namespace std; typedef long long Int; #define REP(i,n) for(int (i)=0;(i)<(int)(n);++(i)) int dx[] = { 0, 1, 0, -1 }; int dy[] = { 1, 0, -1, 0 }; int N, V, SX, SY, GX, GY; int L[100][100]; int best[100][100][3000]; bool isin(int x, int y) { return 0 <= x && x < N && 0 <= y && y < N; } int main() { cin >> N >> V >> SY >> SX >> GY >> GX; SX--; SY--; GX--; GY--; REP(i, N) REP(j, N) cin >> L[i][j]; REP(i, 100)REP(j, 100) REP(k, 3000) best[i][j][k] = -1; queue> q; q.push(make_tuple(SX, SY, 0)); best[SX][SY][0] = 0; int ans = -1; while (!q.empty()) { auto t = q.front(); q.pop(); int x = get<0>(t); int y = get<1>(t); int v = get<2>(t); int step = best[x][y][v]; if (x == GX && y == GY && v < V) { ans = step; break; } REP(i, 4) { int nx = x + dx[i]; int ny = y + dy[i]; if (isin(nx, ny)) { int nv = v + L[nx][ny]; if (nv <= 2 * N * 10 + 100) if (best[nx][ny][nv] == -1) { best[nx][ny][nv] = step + 1; q.push(make_tuple(nx, ny, nv)); } } } } cout << ans << endl; }