import java.util.*; import java.io.*; public class Main { public static void main (String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] first = br.readLine().split(" ", 6); int n = Integer.parseInt(first[0]); int v = Integer.parseInt(first[1]); int sc = Integer.parseInt(first[2]) - 1; int sr = Integer.parseInt(first[3]) - 1; int gc = Integer.parseInt(first[4]) - 1; int gr = Integer.parseInt(first[5]) - 1; int[][] field = new int[n][n]; int[][] costs = new int[n][n]; for (int i = 0; i < n; i++) { String[] line = br.readLine().split(" ", n); for (int j = 0; j < n; j++) { field[i][j] = line[j].charAt(0) - '0'; } Arrays.fill(costs[i], Integer.MAX_VALUE); } PriorityQueue queue = new PriorityQueue<>(); queue.add(new Path(sr, sc, -field[sr][sc], 0)); while (queue.size() > 0) { Path p = queue.poll(); if (p.row < 0 || p.row >= n || p.col < 0 || p.col >= n) { continue; } p.value += field[p.row][p.col]; if (p.value >= v || costs[p.row][p.col] <= p.count) { continue; } costs[p.row][p.col] = p.count; queue.add(new Path(p.row + 1, p.col, p.value, p.count + 1)); queue.add(new Path(p.row - 1, p.col, p.value, p.count + 1)); queue.add(new Path(p.row, p.col + 1, p.value, p.count + 1)); queue.add(new Path(p.row, p.col - 1, p.value, p.count + 1)); } if (costs[gr][gc] == Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(costs[gr][gc]); } } static class Path implements Comparable { int row; int col; int value; int count; public Path(int row, int col, int value, int count) { this.row = row; this.col = col; this.value = value; this.count = count; } public int compareTo(Path another) { return value - another.value; } } }