/* -*- coding: utf-8 -*- * * 34.cc: No.34 砂漠の行商人 - yukicoder */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; /* constant */ const int MAX_N = 100; const int MAX_V = 10000; const int INF = 1 << 30; const int dxs[] = {1, 0, -1, 0}, dys[] = {0, -1, 0, 1}; /* typedef */ typedef map mii; struct Stat { int d, x, y, v; Stat() {} Stat(int _d, int _x, int _y, int _v): d(_d), x(_x), y(_y), v(_v) {} bool operator<(const Stat &s) const { return d > s.d; } }; /* global variables */ int flds[MAX_N][MAX_N]; mii dists[MAX_N][MAX_N]; /* subroutines */ /* main */ int main() { int n, v, sx, sy, gx, gy; cin >> n >> v >> sx >> sy >> gx >> gy; v--, sx--, sy--, gx--, gy--; for (int y = 0; y < n; y++) for (int x = 0; x < n; x++) cin >> flds[y][x]; dists[sy][sx][v] = 0; queue q; q.push(Stat(0, sx, sy, v)); int mind = -1; while (! q.empty()) { Stat u = q.front(); q.pop(); if (u.x == gx && u.y == gy) { mind = u.d; break; } int vd = u.d + 1; for (int di = 0; di < 4; di++) { int vx = u.x + dxs[di], vy = u.y + dys[di]; if (vx >= 0 && vx < n && vy >= 0 && vy < n && u.v >= flds[vy][vx]) { int vv = u.v - flds[vy][vx]; mii::iterator mit = dists[vy][vx].find(vv); if (mit == dists[vy][vx].end()) { dists[vy][vx][vv] = vd; q.push(Stat(vd, vx, vy, vv)); } else if (mit->second > vd) { mit->second = vd; q.push(Stat(vd, vx, vy, vv)); } } } } printf("%d\n", mind); return 0; }