暑假训练 HDU 2102 A计划(两层bfs)

题目描述:
可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。
现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用*表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。
Input
输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小N*M(1 <= N,M <=10)。T如上所意。接下去的前N*M表示迷宫的第一层的布置情况,后N*M表示迷宫第二层的布置情况。
Output
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。

代码如下:

#include<iostream>
#include<cstdio>
#include<string.h>
#include<queue>
using namespace std;

struct point
{
    int x, y, step, type;
}p[105];
char mp[2][12][12];
int m, n, T;
int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

int bfs(point x)
{
    point t, tt;
    queue<point> q;
    q.push(x);
    while(!q.empty())
    {
        t = q.front();
        q.pop();
        if(mp[t.type][t.x][t.y] == '*')continue;
        if(mp[t.type][t.x][t.y] == 'P')return 1;
        mp[t.type][t.x][t.y] = '*';
        for(int i = 0; i < 4; i++)
        {
            tt.x = t.x + dir[i][0];
            tt.y = t.y + dir[i][1];
            tt.step = t.step + 1;
            tt.type = t.type;
            if(tt.step > T || mp[tt.type][tt.x][tt.y] == '*')continue;
            if(mp[tt.type][tt.x][tt.y] == '#')
            {
                mp[tt.type][tt.x][tt.y] == '*';
                tt.type = 1 - tt.type;
                if(mp[tt.type][tt.x][tt.y] == '#' || mp[tt.type][tt.x][tt.y] == '*')
                {
                    mp[tt.type][tt.x][tt.y] = mp[tt.type + 1][tt.x][tt.y] = '*';
                    continue;
                }
            }
            q.push(tt);
        }
    }
    return 0;
}

int main()
{
    int i, j, c;
    point s;
    scanf("%d", &c);
    while(c--)
    {
        memset(mp, '*', sizeof mp);
        cin>> m >> n >> T;
        for(int i = 1; i <= m; i++)
            for(int j = 1; j <= n; j++)
            cin>>mp[0][i][j];
        for(int i = 1; i <= m; i++)
            for(int j = 1; j <= n; j++)
            cin>>mp[1][i][j];
        s.x = 1;
        s.y = 1;
        s.step = 0;
        s.type = 0;
        if(bfs(s))printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

看了大佬的代码,发现这题用bfs写好像更简单,,,
主要细节就是bfs经过传送门或传送门是死路后直接换成 * ,然后节点中保存下所需的时间这样就能轻易判定能否拯救公主了。。。

猜你喜欢

转载自blog.csdn.net/wbl1970353515/article/details/82746997