// 想定解法: 格子点平面上の最短経路探索(Dijkstra, SPFA, etc.) // 各位置での累計移動距離ごとの必要コスト最小化 // もっといい解がありそうな気がするのでつよい人に期待 #include #include #include #include using namespace std; #define REP(i, n) for(int(i)=0;(i)<(n);++(i)) const int MAXN = 100; int board[MAXN][MAXN]; int cost[MAXN][MAXN]; const int INF = 1<<29; const int dir[][2] = {{1,0},{0,1},{-1,0},{0,-1}}; int N, V, SX, SY, GX, GY; int solve(){ REP(y,N) REP(x,N) cost[y][x] = INF; deque,int> > q; q.push_back(make_pair(make_pair(SX,SY),0)); cost[SY][SX] = 0; while(!q.empty()){ auto &v = q.front(); int x = v.first.first, y = v.first.second, s = v.second; q.pop_front(); int nowcost = cost[y][x]; if(x == GX && y == GY) return s; for(int d = 0; d < 4; d++){ int mx = x + dir[d][0]; int my = y + dir[d][1]; if(mx < 0 || my < 0 || mx >= N || my >= N) continue; int nextcost = nowcost + board[my][mx]; if(cost[my][mx] > nextcost && nextcost < V){ cost[my][mx]= nextcost; q.push_back(make_pair(make_pair(mx,my),s+1)); } } } return -1; } int main(){ cin >> N >> V >> SX >> SY >> GX >> GY; REP(y,N) REP(x,N) cin >> board[y][x]; SX--,SY--,GX--,GY--; cout << solve() << endl; return 0; }