using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; class Program { static string ReadLine() { return Console.ReadLine().Trim(); } static int ReadInt() { return int.Parse(Console.ReadLine()); } static int[] ReadInts() { return ReadLine().Split().Select(int.Parse).ToArray(); } static string[] ReadStrings() { return ReadLine().Split(); } static int BFS(int n, int vitality, int srow, int scol, int grow, int gcol, int[,] g) { var memo = new int[n, n]; var q = new Queue>(); // (row, col, vitality, step) q.Enqueue(Tuple.Create(srow, scol, vitality, 0)); while (q.Count > 0) { var t = q.Dequeue(); int row = t.Item1; int col = t.Item2; int v = t.Item3; int step = t.Item4; if (row == grow && col == gcol) return step; if (memo[row, col] > 0 && memo[row, col] >= v) continue; memo[row, col] = v; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (Math.Abs(i) + Math.Abs(j) == 1) { int r = row + i; int c = col + j; if (0 <= r && r < n && 0 <= c && c < n) { int v2 = v - g[r, c]; if (v2 > 0) { q.Enqueue(Tuple.Create(r, c, v2, step + 1)); } } } } } } return -1; } static void Main() { var xs = ReadInts(); int n = xs[0]; int vitality = xs[1]; int sx = xs[2], sy = xs[3]; int gx = xs[4], gy = xs[5]; var g = new int[n, n]; for (int i = 0; i < n; i++) { var s = ReadInts(); for (int j = 0; j < n; j++) { g[i, j] = s[j]; } } Console.WriteLine(BFS(n, vitality, sy-1, sx-1, gy-1, gx-1, g)); } }