main.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <queue>
  4. using namespace std;
  5. const int L = 200;
  6. const int dx[4] = {1, 0, -1, 0};
  7. const int dy[4] = {0, 1, 0, -1};
  8. int s, n, m;
  9. int flag[L][L];
  10. char map[L][L + 1];
  11. struct Pos {
  12. int r;
  13. int c;
  14. bool k;
  15. int t;
  16. Pos(int r = 0, int c = 0, bool k = false, int t = 0)
  17. : r(r), c(c), k(k), t(t){};
  18. bool operator==(const Pos that) const {
  19. return this->r == that.r && this->c == that.c;
  20. }
  21. };
  22. bool is_expandable(int x, int y) {
  23. if (x < 0 || n <= x || y < 0 || m <= y) return false;
  24. if (map[x][y] == '#' || (flag[x][y] & 1) != 0) return false;
  25. return true;
  26. }
  27. int main() {
  28. scanf("%d", &s);
  29. while (s--) {
  30. scanf("%d %d", &n, &m);
  31. Pos r, a;
  32. for (int i = 0; i < n; i++) {
  33. scanf("%s", map[i]);
  34. for (int j = 0; j < m; j++) {
  35. if (map[i][j] == 'a') {
  36. a.r = i;
  37. a.c = j;
  38. a.t = -1;
  39. } else if (map[i][j] == 'r') {
  40. r.r = i;
  41. r.c = j;
  42. }
  43. }
  44. }
  45. queue<Pos> q;
  46. q.push(r);
  47. memset(flag, 0, sizeof(flag));
  48. flag[r.r][r.c] |= 1;
  49. while (!q.empty()) {
  50. Pos &cur = q.front();
  51. q.pop();
  52. if (cur == a) {
  53. a.t = cur.t;
  54. break;
  55. }
  56. if (cur.k == true) {
  57. for (int i = 0; i < 4; i++) {
  58. int nx = cur.r + dx[i];
  59. int ny = cur.c + dy[i];
  60. if (!is_expandable(nx, ny)) continue;
  61. q.push(Pos(nx, ny, false, cur.t + 1));
  62. flag[nx][ny] |= 1;
  63. }
  64. } else if (map[cur.r][cur.c] == 'x') {
  65. if ((flag[cur.r][cur.c] & 2) == 0) {
  66. q.push(Pos(cur.r, cur.c, true, cur.t + 1));
  67. flag[cur.r][cur.c] |= 2;
  68. }
  69. } else {
  70. for (int i = 0; i < 4; i++) {
  71. int nx = cur.r + dx[i];
  72. int ny = cur.c + dy[i];
  73. if (!is_expandable(nx, ny)) continue;
  74. q.push(Pos(nx, ny, false, cur.t + 1));
  75. flag[nx][ny] |= 1;
  76. }
  77. }
  78. }
  79. if (a.t == -1)
  80. printf("Impossible\n");
  81. else
  82. printf("%d\n", a.t);
  83. }
  84. return 0;
  85. }