main.cc 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <queue> // Use priority queue to save your time & life.
  4. using namespace std;
  5. const int N = 100;
  6. const int M = 9;
  7. const int S = 5;
  8. const short dx[4] = {1, 0, -1, 0};
  9. const short dy[4] = {0, 1, 0, -1};
  10. char map[N][N + 1];
  11. short snake[N][N];
  12. bool flag[N][N][M + 1];
  13. struct Pos {
  14. short r;
  15. short c;
  16. short key;
  17. short kill;
  18. int t;
  19. Pos(short r = 0, short c = 0, short key = 0, short kill = 0, int t = 0)
  20. : r(r), c(c), key(key), kill(kill), t(t) {}
  21. bool operator==(const Pos &that) const {
  22. return this->r == that.r && this->c == that.c && this->key == that.key;
  23. }
  24. bool operator<(const Pos &that) const { return this->t > that.t; }
  25. };
  26. int main() {
  27. int n, m;
  28. while (scanf("%d %d", &n, &m) != EOF) {
  29. if (n == 0 && m == 0) break;
  30. Pos sun, tang;
  31. int s = 0;
  32. for (int i = 0; i < n; i++) {
  33. scanf("%s", map[i]);
  34. for (int j = 0; j < n; j++) {
  35. if (map[i][j] == 'T') {
  36. tang.r = i;
  37. tang.c = j;
  38. tang.key = m;
  39. tang.t = -1;
  40. } else if (map[i][j] == 'K') {
  41. sun.r = i;
  42. sun.c = j;
  43. } else if (map[i][j] == 'S') {
  44. snake[i][j] = s++;
  45. }
  46. }
  47. }
  48. priority_queue<Pos> q;
  49. q.push(sun);
  50. memset(flag, 0, sizeof(flag));
  51. flag[sun.r][sun.c][0] = true;
  52. while (!q.empty()) {
  53. Pos cur = q.top();
  54. q.pop();
  55. if (cur == tang) {
  56. tang.t = cur.t;
  57. break;
  58. }
  59. for (int i = 0; i < 4; i++) {
  60. int nx = cur.r + dx[i];
  61. int ny = cur.c + dy[i];
  62. if (nx < 0 || n <= nx || ny < 0 || n <= ny) continue;
  63. char grid = map[nx][ny];
  64. if (grid == '#') continue;
  65. if (grid == 'S') {
  66. if (flag[nx][ny][cur.key]) continue;
  67. if (cur.kill & (1 << snake[nx][ny]))
  68. q.emplace(nx, ny, cur.key, cur.kill, cur.t + 1);
  69. else
  70. q.emplace(nx, ny, cur.key, cur.kill | (1 << snake[nx][ny]),
  71. cur.t + 2);
  72. flag[nx][ny][cur.key] = true;
  73. } else {
  74. if (!flag[nx][ny][cur.key]) {
  75. q.emplace(nx, ny, cur.key, cur.kill, cur.t + 1);
  76. flag[nx][ny][cur.key] = true;
  77. }
  78. if ('1' <= grid && grid <= '9' && grid - '0' == cur.key + 1 &&
  79. !flag[nx][ny][grid - '0']) { // Get key
  80. q.emplace(nx, ny, grid - '0', cur.kill, cur.t + 1);
  81. flag[nx][ny][grid - '0'] = true;
  82. }
  83. }
  84. }
  85. }
  86. if (tang.t == -1)
  87. printf("impossible\n");
  88. else
  89. printf("%d\n", tang.t);
  90. }
  91. return 0;
  92. }