1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include <cstring> #include <cstdio> #include <algorithm> #include <iostream> #include <unordered_map> #include <queue>
using namespace std;
const int N = 110;
struct node { int x, y, k, d; node(int xx, int yy, int kk, int dd) { x = xx; y = yy; k = kk; d = dd; } friend bool operator<(node a, node b) { return a.d > b.d; } };
int n, m, ans; int kx, ky, tx, ty; char s[N][N]; bool st[N][N][15]; int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1}; priority_queue<node> q;
int bfs() { node start(kx, ky, 0, 0);
st[kx][ky][0] = true;
q.push(start);
while (!q.empty()) { node t = q.top(); q.pop(); int x = t.x, y = t.y, key = t.k, d = t.d;
if (x == tx && y == ty && key == m) ans = min(ans, d);
for (int j = 0; j < 4; j++) { int xx = x + dx[j], yy = y + dy[j];
if (xx >= 1 && xx <= n && yy >= 1 && yy <= n && s[xx][yy] != '#' && !st[xx][yy][key]) { char c = s[xx][yy]; int kk = 0, ss = 1; if (c == 'S') ss++; if (c - '0' - key == 1) kk++;
q.push(node(xx, yy, key + kk, d + ss)); st[xx][yy][key] = true; } } } return 0; }
int main() { while (cin >> n >> m && n && m) { ans = 0x3f3f3f3f;
memset(st, 0, sizeof st);
for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) { cin >> s[i][j];
if (s[i][j] == 'K') kx = i, ky = j; if (s[i][j] == 'T') tx = i, ty = j; }
bfs();
if (ans == 0x3f3f3f3f) cout << "impossible" << "\n"; else cout << ans << "\n";
while (!q.empty()) q.pop(); } return 0; }
|