import std.algorithm, std.array, std.container, std.range, std.bitmanip; import std.numeric, std.math, std.bigint, std.random; import std.string, std.conv, std.stdio, std.typecons; struct point { int x; int y; point opBinary(string op)(point rhs) { static if (op == "+") return point(x + rhs.x, y + rhs.y); else static if (op == "-") return point(x - rhs.x, y - rhs.y); } } const auto sibPoints = [point(-1, 0), point(0, -1), point(1, 0), point(0, 1)]; struct pointWeight { point p; int weight; int opCmp(pointWeight rhs) { return weight == rhs.weight ? 0 : (weight < rhs.weight ? -1 : 1); } } struct pointLen { point p; int len; } void main() { auto rd = readln.split.map!(to!int); auto n = rd[0], v = rd[1]; auto s = point(rd[2] - 1, rd[3] - 1), g = point(rd[4] - 1, rd[5] - 1); auto lij = iota(n).map!(_ => readln.split.map!(to!int).array).array; auto mij = dijkstra(n, lij, g); bool valid(point p) { return p.x >= 0 && p.x < n && p.y >= 0 && p.y < n; } auto cij = new int[][](n, n); cij.each!(a => a[] = -1); cij[s.y][s.x] = 0; auto minLen = -1; auto qi = DList!pointLen(pointLen(s, 0)); while (!qi.empty) { auto q = qi.front, p = q.p, l = q.len; qi.removeFront; if (p == g) { minLen = l; break; } foreach (sib; sibPoints) { auto np = p + sib; if (!valid(np)) continue; auto nw = cij[p.y][p.x] + lij[np.y][np.x]; if (nw >= v) continue; if (cij[np.y][np.x] < 0 || cij[np.y][np.x] > nw) { cij[np.y][np.x] = nw; qi.insertBack(pointLen(np, l + 1)); } } } writeln(minLen); } int[][] dijkstra(int n, int[][] lij, point s) { auto r = new int[][](n, n); r.each!((a) { a[] = -1; }); r[s.y][s.x] = 0; auto qi = heapify!("a > b")(Array!pointWeight()); void addPointWeight(pointWeight pw) { bool valid(point p) { return p.x >= 0 && p.x < n && p.y >= 0 && p.y < n; } auto p = pw.p, w = pw.weight; foreach (sib; sibPoints) { auto np = p + sib; if (!valid(np)) continue; auto nw = w + lij[np.y][np.x]; if (r[np.y][np.x] < 0 || nw < r[np.y][np.x]) { r[np.y][np.x] = nw; qi.insert(pointWeight(np, nw)); } } } addPointWeight(pointWeight(s, 0)); while (!qi.empty) { auto pw = qi.front, p = pw.p, w = pw.weight; qi.removeFront; addPointWeight(pw); } return r; }