#include #include using namespace std; #define FOR(i,a,b) for(int i=(a); i<(b); i++) #define P pair #define PP pair int main(){ // 辺の長さ,体力,スタート地点の座標,ゴール地点の座標 int n, v, sx, sy, gx, gy; cin >> n >> v >> sx >> sy >> gx >> gy; sx--; sy--; gx--; gy--; int map[n][n]; // bfs[x][y][消費コスト] = 移動回数 int bfs[n][n][v]; FOR(i, 0, n){ FOR(j, 0, n){ FOR(k, 0, v) bfs[i][j][k] = -1; } } // 移動方向 int dx[4] = {1, -1, 0, 0}; int dy[4] = {0, 0, 1, -1}; FOR(i, 0, n){ FOR(j, 0, n) cin >> map[j][i]; } queue q; q.push(make_pair(make_pair(sx, sy), 0)); bfs[sx][sy][0] = 0; while(!(q.empty())){ PP pp = q.front(); q.pop(); int x = pp.first.first; int y = pp.first.second; int cost = pp.second; int next_x, next_y, next_cost; // ゴール if (x == gx && y == gy) { cout << bfs[x][y][cost] << endl; return 0; } FOR(i, 0, 4){ next_x = x + dx[i]; next_y = y + dy[i]; // はみ出る場合 if (!(0 <= next_x && next_x < n && 0 <= next_y && next_y < n)) continue; // 体力切れ next_cost = pp.second + map[next_x][next_y]; if (next_cost >= v) continue; // bfsを続ける if (bfs[next_x][next_y][next_cost] == -1){ bfs[next_x][next_y][next_cost] = bfs[x][y][cost] + 1; q.push(make_pair(make_pair(next_x, next_y), next_cost)); } } } cout << -1 << endl; return 0; }