#include using namespace std; const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1}; struct Edge{ int node,cost; Edge(int node, int cost):node(node),cost(cost){ } }; struct State{ int hp,node; int cost; State(int node, int hp, int cost):hp(hp),node(node),cost(cost){} bool operator < (const State& right) const { return cost > right.cost; } }; int N,V,sx,sy,gx,gy; int board[110][110]; int cost[10010][10010]; vector Edges[10010]; int main(){ cin >> N >> V >> sx >> sy >> gx >> gy; sx--; sy--; gx--; gy--; for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ cin >> board[i][j]; } } for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ int ny,nx; int node = i * N + j; for (int k = 0; k < 4; k++){ ny = i + dy[k]; nx = j + dx[k]; if (ny < 0 or nx < 0 or ny >= N or nx >= N)continue; int next_node = ny * N + nx; int cost = board[ny][nx]; Edges[node].push_back(Edge(next_node, cost)); } } } priority_queue que; que.push(State(sy * N + sx, V, false)); for (int i = 0; i < 10010; i++){ for (int j = 0; j < 10000; j++){ cost[i][j] = 1LL << 30; } } cost[sy * N + sx][V] = 0; long long ans = 1LL << 40; while (!que.empty()){ State pos = que.top(); que.pop(); //cout << pos.node << " " << pos.hp << endl; if (cost[pos.node][pos.hp] > pos.cost or ans < pos.cost){ continue; } if (pos.node == gy * N + gx){ ans = min(ans, (long long)pos.cost); continue; } for (int i = 0; i < Edges[pos.node].size(); i++){ Edge np = Edges[pos.node][i]; if (pos.hp - np.cost > 0){ if (cost[np.node][pos.hp - np.cost] > cost[pos.node][pos.hp] + 1){ cost[np.node][pos.hp - np.cost] = cost[pos.node][pos.hp] + 1; que.push(State(np.node, pos.hp - np.cost, cost[np.node][pos.hp - np.cost])); } } } } if (ans == 1LL << 40){ cout << -1 << endl; return 0; } cout << ans << endl; return 0; }