import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Iterator; import java.util.Queue; public class Main_yukicoder34 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Printer pr = new Printer(System.out); int[] dx = {1, -1, 0, 0}; int[] dy = {0, 0, 1, -1}; int n = sc.nextInt(); int v = sc.nextInt(); int sx = sc.nextInt() - 1; int sy = sc.nextInt() - 1; int gx = sc.nextInt() - 1; int gy = sc.nextInt() - 1; int[][] l = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { l[i][j] = sc.nextInt(); } } int[][] vv = new int[n][n]; Queue qx = new ArrayDeque<>(); Queue qy = new ArrayDeque<>(); Queue qv = new ArrayDeque<>(); qx.add(sx); qy.add(sy); qv.add(v); vv[sy][sx] = v; for (int cnt = 0; true; cnt++) { Queue qxtmp = new ArrayDeque<>(); Queue qytmp = new ArrayDeque<>(); Queue qvtmp = new ArrayDeque<>(); while (!qx.isEmpty()) { int x = qx.remove(); int y = qy.remove(); int vtmp = qv.remove(); if (x == gx && y == gy && vtmp > 0) { pr.println(cnt); pr.close(); sc.close(); return; } for (int i = 0; i < dx.length; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (nx >= 0 && nx < n && ny >= 0 && ny < n) { int nv = vtmp - l[ny][nx]; if (nv > 0 && nv > vv[ny][nx]) { qxtmp.add(nx); qytmp.add(ny); qvtmp.add(nv); vv[ny][nx] = nv; } } } } if (!qxtmp.isEmpty()) { // pr.println(qxtmp.size()); qx = qxtmp; qy = qytmp; qv = qvtmp; } else { break; } } pr.println(-1); pr.close(); sc.close(); } @SuppressWarnings("unused") private static class Scanner { BufferedReader br; Iterator it; Scanner (InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } String next() throws RuntimeException { try { if (it == null || !it.hasNext()) { it = Arrays.asList(br.readLine().split(" ")).iterator(); } return it.next(); } catch (IOException e) { throw new IllegalStateException(); } } int nextInt() throws RuntimeException { return Integer.parseInt(next()); } long nextLong() throws RuntimeException { return Long.parseLong(next()); } float nextFloat() throws RuntimeException { return Float.parseFloat(next()); } double nextDouble() throws RuntimeException { return Double.parseDouble(next()); } void close() { try { br.close(); } catch (IOException e) { // throw new IllegalStateException(); } } } private static class Printer extends PrintWriter { Printer(PrintStream out) { super(out); } } }