[kuangbin带你飞]专题二 搜索进阶 I - A计划(HDU 2102)

题目链接I - A计划
思路:

还是正常的bfs,多了一层而已。在移动时,增加判断,如果下一步为时光传输机且对应的节点为空地,则加入队列,否则continue即可。

代码:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <queue>
#include <string.h>
#include <set>
#include <stack>
#include <stdlib.h>
#include <time.h>

using namespace std;

int mp[2][12][12];

typedef struct Node
{
    int x, y, z;
    int num;
}node;

int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};

bool bfs(int x, int y, int z, int time)
{
    node temp;
    temp.x = 1;
    temp.y = 1;
    temp.z = 0;
    temp.num = 0;
    queue<node> q;
    q.push(temp);
    while(!q.empty())
    {
        temp = q.front();
        //cout<<temp.x<<" "<<temp.y<<" "<<temp.z<<" "<<temp.num<<endl;
        if(temp.num > time)
            break;
        if(temp.x == x && temp.y == y && temp.z == z)
            return true;
        q.pop();

        for(int i=0;i<4;i++)
        {
            node t;
            t.x = temp.x + dx[i];
            t.y = temp.y + dy[i];
            t.z = temp.z;
            t.num = temp.num + 1;
            if(mp[t.z][t.x][t.y] == 2)
            {
                mp[t.z][t.x][t.y] = 0;
                if(mp[!t.z][t.x][t.y] == 1)
                {
                    mp[!t.z][t.x][t.y] = 0;
                    t.z ^= 1;
                    q.push(t);
                }
                else
                    continue;
            }
            else if(mp[t.z][t.x][t.y] == 1)
            {
                mp[t.z][t.x][t.y]--;
                q.push(t);
            }
        }
    }
    return false;
}

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int n, m, time, sx, sy, sz;
        cin>>n>>m>>time;
        char t[12];
        memset(mp, 0, sizeof(mp));
        for(int ti=0;ti<=1;ti++)
            for(int i=1;i<=n;i++)
            {
                cin>>t;
                for(int j=0;j<m;j++)
                    if(t[j] == 'P')
                    {
                        sx = i;
                        sy = j+1;
                        sz = ti;
                        mp[ti][i][j+1] = 1;
                    }
                    else if(t[j] == '#')
                        mp[ti][i][j+1] = 2;
                    else if(t[j] == '.')
                        mp[ti][i][j+1] = 1;
            }
        if(bfs(sx, sy, sz, time))
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
    return 0;
}

你可能感兴趣的:(搜索,bfs)