#include #include #include #include #include using namespace std; int n, v; struct Node { int node; int depth; int distance; Node(int node, int depth, int distance) : node(node), depth(depth), distance(distance) {} }; int shortest(const vector >& costs, int nodeCount, int startNode, int endNode) { queue q; vector distances(nodeCount, numeric_limits::max()); q.push(Node(startNode, 0, 0)); while (!q.empty()) { Node node = q.front(); q.pop(); if (distances[node.node] > node.distance) { distances[node.node] = node.distance; if (node.node == endNode && node.distance < v) { return node.depth; } for (map::const_iterator it = costs[node.node].begin(); it != costs[node.node].end(); ++it) { q.push(Node(it->first, node.depth + 1, node.distance + it->second)); } } } return -1; } int index(int x, int y) { return (x - 1) + (y - 1) * n; } int main() { int sx, sy, gx, gy; cin >> n >> v >> sx >> sy >> gx >> gy; vector > l(n + 1, vector(n + 1)); for (int y = 1; y <= n; ++y) { for (int x = 1; x <= n; ++x) { cin >> l[x][y]; } } int nodeCount = n * n; vector > edges(nodeCount); for (int y = 1; y <= n; ++y) { for (int x = 1; x <= n; ++x) { if (x > 1) { edges[index(x - 1, y)][index(x, y)] = l[x][y]; } if (x < n) { edges[index(x + 1, y)][index(x, y)] = l[x][y]; } if (y > 1) { edges[index(x, y - 1)][index(x, y)] = l[x][y]; } if (y < n) { edges[index(x, y + 1)][index(x, y)] = l[x][y]; } } } int result = shortest(edges, nodeCount, index(sx, sy), index(gx, gy)); cout << result << endl; return 0; }