#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define INF_MIN 100000000 #define INF 1145141919 #define INF_MAX 2147483647 #define LL_MAX 9223372036854775807 #define EPS 1e-10 #define PI acos(-1) #define LL long long using namespace std; #define MAX_N 101 #define MAX_V 10001 int N, V, Sx, Sy, Gx, Gy; int maze[MAX_N][MAX_N]; int dp[MAX_N][MAX_N][MAX_V]; int dx[] = {1,0,-1,0}; int dy[] = {0,1,0,-1}; typedef pair P; typedef pair PP; int solve(){ dp[Sy][Sx][V] = 0; queue que; que.push(PP(P(Sx, Sy), P(V, -1))); while(que.size()){ PP p = que.front(); que.pop(); int x = p.first.first, y = p.first.second; int v = p.second.first; int preDir = p.second.second; if(Gx == x && Gy == y) return dp[y][x][v]; for(int d = 0; d < 4; d++){ if(d == preDir) continue; int nx = x + dx[d]; int ny = y + dy[d]; int nextDir = (d + 2) % 4; if(0 <= nx && nx < N && 0 <= ny && ny < N){ int nextV = v - maze[ny][nx]; if(nextV > 0 && dp[ny][nx][nextV] > dp[y][x][v] + 1){ dp[ny][nx][nextV] = dp[y][x][v] + 1; que.push(PP(P(nx, ny), P(nextV, nextDir))); } } } } return -1; } 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 >> maze[i][j]; for(int k = 0; k <= V; k++){ dp[i][j][k] = INF; } } } cout << solve() << endl; return 0; }