HDU 1254 - 推箱子(BFS + DFS)

来源:互联网 发布:安卓微信数据恢复软件 编辑:程序博客网 时间:2024/06/05 05:20

思路

这题做得好蛋疼啊。

一开始不知道给出人的位置是什么用的,后来才知道有的位置是推不过去的。

后来采用了BFS + DFS,还是一直WA。因为我每次都是人最开始的位置DFS,有的时候本来可以推的变成不能推了。才想到要记录人推的位置。

BFS判断箱子能不能到达位置,DFS判断人能不能走到。

代码写得很丑TAT

代码

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <queue>
  4. #define LL long long
  5. #define lowbit(x) ((x) & (-x))
  6. const int MAXN = 10;
  7. const int INF = 0x3f3f3f3f;
  8. const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
  9. using namespace std;
  10. struct POINT
  11. {
  12. int x, y, dis;
  13. int xlast, ylast;
  14. };
  15. int mp[MAXN][MAXN], vis[MAXN][MAXN][4], row, col, cVis[MAXN][MAXN];
  16. queue<POINT> qu;
  17. int st, ed;
  18. POINT boxSt, peo;
  19. bool Check(int x, int y, int xcur, int ycur)
  20. {
  21. if (x == st && y == ed)
  22. return true;
  23. cVis[x][y] = 1;
  24. for (int i = 0; i < 4; i++)
  25. {
  26. int xx = x + dir[i][0], yy = y + dir[i][1];
  27. if (xx >= 1 && xx <= row && yy >= 1 && yy <= col && !cVis[xx][yy] && mp[xx][yy] != 1 && !(xx == xcur && yy == ycur))
  28. if (Check(xx, yy, xcur, ycur))
  29. return true;
  30. }
  31. return false;
  32. }
  33. int BFS(POINT boxSt)
  34. {
  35. bool first = true;
  36. memset(vis, 0, sizeof vis);
  37. while (!qu.empty())
  38. qu.pop();
  39. qu.push(boxSt);
  40. while (!qu.empty())
  41. {
  42. POINT cur = qu.front(); qu.pop();
  43. if (mp[cur.x][cur.y] == 3)
  44. return cur.dis;
  45. for (int i = 0; i < 4; i++) //0, 1, 2, 3, up, down, left, right
  46. {
  47. int x = cur.x + dir[i][0], y = cur.y + dir[i][1];
  48. if (mp[x][y] != 1 && x >= 1 && x <= row && y >= 1 && y <= col && !vis[x][y][i])
  49. {
  50. st = cur.x - dir[i][0], ed = cur.y - dir[i][1];
  51. memset(cVis, 0, sizeof cVis);
  52. cVis[peo.x][peo.y] = 1;
  53. POINT temp; temp.x = x, temp.y = y, temp.dis = cur.dis + 1;
  54. temp.xlast = cur.x, temp.ylast = cur.y;
  55. if (Check(cur.xlast, cur.ylast, cur.x, cur.y))
  56. {
  57. vis[x][y][i] = 1;
  58. qu.push(temp);
  59. }
  60. }
  61. }
  62. }
  63. return -1;
  64. }
  65. int main()
  66. {
  67. //freopen("input.txt", "r", stdin);
  68. int i, j, T;
  69. scanf("%d", &T);
  70. while (T--)
  71. {
  72. boxSt.dis = 0;
  73. scanf("%d%d", &row, &col);
  74. for (i = 1; i <= row; i++)
  75. for (j = 1; j <= col; j++)
  76. {
  77. scanf("%d", &mp[i][j]);
  78. if (mp[i][j] == 2)
  79. boxSt.x = i, boxSt.y = j;
  80. if (mp[i][j] == 4)
  81. boxSt.xlast = i, boxSt.ylast = j;
  82. }
  83. printf("%d\n", BFS(boxSt));
  84. }
  85. return 0;
  86. }
1 0
原创粉丝点击