BFS HDOJ 1728 逃离迷宫

 

题目传送门

 1 /*  2  BFS:三维BFS,加上方向。用dp[x][y][d]记录当前需要的最少转向数  3 */  4 #include <cstdio>  5 #include <algorithm>  6 #include <cstring>  7 #include <queue>  8 #include <cmath>  9 using namespace std;  10  11 const int MAXN = 1e2 + 10;  12 const int INF = 0x3f3f3f3f;  13 struct P  14 {  15 int x, y, z;  16 }now, to;  17 char maze[MAXN][MAXN];  18 int dp[MAXN][MAXN][4];  19 bool inq[MAXN][MAXN][4];  20 int dx[4] = {-1, 1, 0, 0};  21 int dy[4] = {0, 0, -1, 1};  22 int k, x1, y1, x2, y2;  23 int n, m;  24  25 bool check(int x, int y)  26 {  27 if (x >= 1 && x <= n && y >= 1 && y <= m) return true;  28 else return false;  29 }  30  31 bool BFS(void)  32 {  33 memset (dp, 0, sizeof (dp));  34 memset (inq, false, sizeof (inq));  35 queue<P> Q;  36 for (int i=1; i<=n; ++i)  37  {  38 for (int j=1; j<=m; ++j)  39  {  40 for (int l=0; l<4; ++l)  41  {  42 dp[i][j][l] = INF; inq[i][j][l] = false;  43  }  44  }  45  }  46 for (int i=0; i<4; ++i)  47  {  48 dp[x1][y1][i] = 0; inq[x1][y1][i] = true;  49  Q.push ((P) {x1, y1, i});  50  }  51  52 while (!Q.empty ())  53  {  54 now = Q.front (); Q.pop ();  55 for (int i=0; i<4; ++i)  56  {  57 to.x = now.x + dx[i];  58 to.y = now.y + dy[i]; to.z = i;  59 if (check (to.x, to.y) && maze[to.x][to.y] == '.')  60  {  61 int tmp = dp[now.x][now.y][now.z];  62 if (to.z == now.z)  63  {  64 if (tmp < dp[to.x][to.y][to.z])  65  {  66 dp[to.x][to.y][to.z] = tmp;  67 if (!inq[to.x][to.y][to.z])  68  {  69 inq[to.x][to.y][to.z] = true; Q.push (to);  70  }  71  }  72  }  73 else  74  {  75 if (++tmp < dp[to.x][to.y][to.z])  76  {  77 dp[to.x][to.y][to.z] = tmp;  78 if (!inq[to.x][to.y][to.z])  79  {  80 inq[to.x][to.y][to.z] = true; Q.push (to);  81  }  82  }  83  }  84  }  85  }  86 inq[now.x][now.y][now.z] = false;  87  }  88  89 for (int i=0; i<4; ++i)  90  {  91 if (dp[x2][y2][i] <= k) return true;  92  }  93  94 return false;  95 }  96  97 int main(void) //HDOJ 1728 逃离迷宫  98 {  99 // freopen ("HDOJ_1728.in", "r", stdin); 100 101 int t; scanf ("%d", &t); 102 while (t--) 103  { 104 scanf ("%d%d", &n, &m); 105 for (int i=1; i<=n; ++i) scanf ("%s", maze[i] + 1); 106 scanf ("%d%d%d%d%d", &k, &y1, &x1, &y2, &x2); 107 if (BFS ()) puts ("yes"); 108 else puts ("no"); 109  } 110 111 return 0; 112 }

 

你可能感兴趣的:(bfs)