import java.util.* fun main(arr:Array) { val inpt = readLine()!!.trim().split(" ").map { it.toInt() } val (n, v) = inpt.take(2) val (sx, sy, gx, gy) = inpt.drop(2).map { it - 1 } val map = (1..n).map { readLine()!!.split(" ").map { it.toInt() }.toTypedArray() }.toTypedArray() val step = map.map { it.map { mutableMapOf() }.toTypedArray() }.toTypedArray() val queue = LinkedList() var min = n * n + 1 queue.add(Task(sx, sy, v, 0)) while (queue.isNotEmpty()) { val t = queue.pop() if(t.vital <= 0) { continue } if(t.step > min) { continue } var skip = false step[t.y][t.x][t.vital]?.also { if(it <= t.step) { skip = true } } if(skip) { continue } else { step[t.y][t.x][t.vital] = t.step } if(t.x == gx && t.y == gy) { min = Math.min(min, t.step) continue } if(t.y > 0) { queue.add(Task(t.x, t.y - 1, t.vital - map[t.y - 1][t.x], t.step + 1)) } if(t.y < n - 1) { queue.add(Task(t.x, t.y + 1, t.vital - map[t.y + 1][t.x], t.step + 1)) } if(t.x > 0) { queue.add(Task(t.x - 1, t.y, t.vital - map[t.y][t.x - 1], t.step + 1)) } if(t.x < n - 1) { queue.add(Task(t.x + 1, t.y, t.vital - map[t.y][t.x + 1], t.step + 1)) } } var ans = -1 if(step[gy][gx].isNotEmpty()) { ans = step[gy][gx].values.min()!! } println(ans) } data class Task(val x:Int, val y:Int, val vital:Int, val step:Int)