您的位置:首页 > 其它

BFS HDOJ 1728 逃离迷宫

2015-07-18 14:09 477 查看
题目传送门

 /*
BFS:三维BFS,加上方向。用dp[x][y][d]记录当前需要的最少转向数
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cmath>
using namespace std;

const int MAXN = 1e2 + 10;
const int INF = 0x3f3f3f3f;
struct P
{
int x, y, z;
}now, to;
char maze[MAXN][MAXN];
int dp[MAXN][MAXN][4];
bool inq[MAXN][MAXN][4];
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int k, x1, y1, x2, y2;
int n, m;

bool check(int x, int y)
{
if (x >= 1 && x <= n && y >= 1 && y <= m)    return true;
else    return false;
}

bool BFS(void)
{
memset (dp, 0, sizeof (dp));
memset (inq, false, sizeof (inq));
queue<P> Q;
for (int i=1; i<=n; ++i)
{
for (int j=1; j<=m; ++j)
{
for (int l=0; l<4; ++l)
{
dp[i][j][l] = INF;    inq[i][j][l] = false;
}
}
}
for (int i=0; i<4; ++i)
{
dp[x1][y1][i] = 0;    inq[x1][y1][i] = true;
Q.push ((P) {x1, y1, i});
}

while (!Q.empty ())
{
now = Q.front ();    Q.pop ();
for (int i=0; i<4; ++i)
{
to.x = now.x + dx[i];
to.y = now.y + dy[i];    to.z = i;
if (check (to.x, to.y) && maze[to.x][to.y] == '.')
{
int tmp = dp[now.x][now.y][now.z];
if (to.z == now.z)
{
if (tmp < dp[to.x][to.y][to.z])
{
dp[to.x][to.y][to.z] = tmp;
if (!inq[to.x][to.y][to.z])
{
inq[to.x][to.y][to.z] = true;    Q.push (to);
}
}
}
else
{
if (++tmp < dp[to.x][to.y][to.z])
{
dp[to.x][to.y][to.z] = tmp;
if (!inq[to.x][to.y][to.z])
{
inq[to.x][to.y][to.z] = true;    Q.push (to);
}
}
}
}
}
inq[now.x][now.y][now.z] = false;
}

for (int i=0; i<4; ++i)
{
if (dp[x2][y2][i] <= k)    return true;
}

return false;
}

int main(void)        //HDOJ 1728 逃离迷宫
{
//    freopen ("HDOJ_1728.in", "r", stdin);

int t;    scanf ("%d", &t);
while (t--)
{
scanf ("%d%d", &n, &m);
for (int i=1; i<=n; ++i)    scanf ("%s", maze[i] + 1);
scanf ("%d%d%d%d%d", &k, &y1, &x1, &y2, &x2);
if (BFS ())    puts ("yes");
else    puts ("no");
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: