using System; using System.Collections.Generic; namespace No34{ public class Program{ public static void Main(string[] args){ var sr = new StreamReader(); //--------------------------------- var N = sr.Next(); var V = sr.Next(); var Sx = sr.Next() - 1; var Sy = sr.Next() - 1; var Gx = sr.Next() - 1; var Gy = sr.Next() - 1; var L = sr.Next(N, N); Func isInside = (x, y) => 0 <= x && x < N && 0 <= y && y < N; var dx = new[]{0, 1, 0, -1}; var dy = new[]{1, 0, -1, 0}; var dist = new int[V + 1, N, N]; var que = new Queue(); dist[V, Sx, Sy] = 1; que.Enqueue(V); que.Enqueue(Sx); que.Enqueue(Sy); while(que.Count > 0){ var v = que.Dequeue(); var x = que.Dequeue(); var y = que.Dequeue(); for(var i = 0; i < 4; i++){ var nx = x + dx[i]; var ny = y + dy[i]; if(isInside(nx, ny)){ var nv = v - L[ny][nx]; if(nv <= 0) continue; if(dist[nv, nx, ny] != 0 && dist[nv, nx, ny] <= dist[v, x, y] + 1) continue; que.Enqueue(nv); que.Enqueue(nx); que.Enqueue(ny); dist[nv, nx, ny] = dist[v, x, y] + 1; } } } var min = int.MaxValue; for(var i = 0; i <= V; i++){ if(dist[i, Gx, Gy] != 0) min = Math.Min(min, dist[i, Gx, Gy]); } Console.WriteLine(min != int.MaxValue ? min - 1 : -1); //--------------------------------- } } public class StreamReader{ private readonly char[] _c = {' '}; private int _index = -1; private string[] _input = new string[0]; public T Next(){ if(_index == _input.Length - 1){ _index = -1; while(true){ string rl = Console.ReadLine(); if(rl == null){ if(typeof(T).IsClass) return default(T); return (T)typeof(T).GetField("MinValue").GetValue(null); } if(rl != ""){ _input = rl.Split(_c, StringSplitOptions.RemoveEmptyEntries); break; } } } return (T)Convert.ChangeType(_input[++_index], typeof(T), System.Globalization.CultureInfo.InvariantCulture); } public T[] Next(int x){ var ret = new T[x]; for(var i = 0; i < x; ++i) ret[i] = Next(); return ret; } public T[][] Next(int y, int x){ var ret = new T[y][]; for(var i = 0; i < y; ++i) ret[i] = Next(x); return ret; } } }