#include using namespace std; int N, V, Sx, Sy, Gx, Gy; int m[100][100]; map ans_p[100][100]; map ans_v[100][100]; int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; bool range_check(int y, int x, int h, int w = -1) { if(w < 0) w = h; return (0 <= x && x < w && 0 <= y && y < h); } template std::pair get_min( const std::map& x ) { using pairtype=std::pair; return *std::min_element(x.begin(), x.end(), [] (const pairtype & p1, const pairtype & p2) { return p1.second < p2.second; }); } void recursive(int y, int x, int v, int p) { // 死亡または不要な解 if(v <= 0) return; if (ans_p[y][x].count(v) > 0 && ans_p[y][x][v] <= p) return; if (ans_v[y][x].count(p) > 0 && ans_v[y][x][p] >= v) return; ans_p[y][x][v] = p; ans_v[y][x][p] = v; for(int d = 0; d < 4; d++) { int ny = y + dir[d][0]; int nx = x + dir[d][1]; if(!range_check(ny, nx, N)) continue; recursive(ny, nx, v - m[ny][nx], p + 1); } } int main() { #ifdef DEBUG std::ifstream in("/home/yusuke/inputf.in"); std::cin.rdbuf(in.rdbuf()); #endif 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 >> m[i][j]; ans_p[i][j] = map(); ans_v[i][j] = map(); } } recursive(Sy, Sx, V, 0); if (ans_p[Gy][Gx].empty()) { cout << -1 << endl; } else { cout << get_min(ans_p[Gy][Gx]).second << endl; } return 0; }