from collections import * inf = 10 ** 18 N, V, sx, sy, gx, gy = map(int, input().split()) sx, sy, gx, gy = sx-1, sy-1, gx-1, gy-1 d = abs(sx - gx) + abs(sy - gy) L = [] for i in range(N): L.append(list(map(int, input().split()))) if V > d * 9: print(d) exit() def f(x, y, v): return x + y * N + v * N * N def g(n): v = n // (N * N) n %= N * N y, x = divmod(n, N) return x, y, v dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] Q = deque([]) dist = defaultdict(lambda:inf) val = [[-1] * N for i in range(N)] s = f(sy, sx, V) dist[s] = 0 Q.append(s) x, y, vv = g(s) val[sy][sx] = V while Q: u = Q.popleft() px, py, vv = g(u) for k in range(4): x = px + dx[k] y = py + dy[k] if x < 0 or x > N - 1 or y < 0 or y > N - 1: continue if vv - L[x][y] <= 0: continue if val[x][y] > vv: continue v = f(x, y, vv - L[x][y]) if v in dist: continue dist[v] = dist[u] + 1 if x == gy and y == gx: print(dist[v]) exit() Q.append(v) ans = inf for v in range(1, V + 1): ans = min(ans, dist[f(gy, gx, v)]) print(ans) if ans != inf else print(-1)