hdu 1242 Rescue

bfs的拓展應用就是搜索無論是形式,關鍵在於狀態的轉移,和動態規劃一樣,如何劃分狀態是解決問題的關鍵。
這個題是尋求最少的時間,由於有坑點r可能有多個,就要反向搜索,將a點作爲起點進行搜索,再將r點的座標記錄,利用動態規劃的思想將每個點的可達最小值記錄,然後求個最小值就可以了。


#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int MAXN = 400 + 10;
const int MAX = 0x3f3f3f3f;
struct A
{
    int x,y;
    int time;
};
struct P
{
    int x,y;
};
char _map[MAXN][MAXN];
int dp[MAXN][MAXN];
bool tag[MAXN][MAXN];
int ans[400][2];
int f[4][2] = {0,-1,-1,0,0,1,1,0};
int main()
{
    int n,m;
    while(cin >> n >> m)
    {
        queue<A> que;
        P ans[5000];
        int cnt = 0;
        memset(_map,0,sizeof(_map));
        int x,y,obj_a = -1,obj_b = -1;
        for(int i = 1;i <= n;++i)
        {
            for(int j = 1; j <= m;++j)
            {
                cin >> _map[i][j];
                if(_map[i][j] == 'r')
                {
                    ans[cnt].x = i;
                    ans[cnt].y = j;
                    cnt++;
                }
                if(_map[i][j] == 'a')
                {
                    obj_a = i; obj_b = j;
                }
                dp[i][j] = MAX;
            }
        }
        if(obj_a == -1)
        {
            cout << "Poor ANGEL has to stay in the prison all his life." << endl;
            continue;
        }
        dp[obj_a][obj_b] = 0;
        A temp;
        temp.time = 0;
        temp.x = obj_a; temp.y = obj_b;
        que.push(temp);
        int xa,ya;
        while(!que.empty())
        {
            for(int i = 0;i <= 3;++i)
            {
                xa = que.front().x + f[i][0];
                ya = que.front().y + f[i][1];
                if(xa >= 1 && xa <= n && ya >= 1 && ya <= m )
                {
                    if(_map[xa][ya] != '#')
                    {
                        temp.time = que.front().time + 1;
                        temp.x = xa; temp.y = ya;
                        if(_map[xa][ya] == 'x')
                        {
                            temp.time++;
                        }
                        if(temp.time < dp[xa][ya])
                        {
                            dp[xa][ya] = temp.time;
                            que.push(temp);
                        }
                    }
                }
            }
            que.pop();
        }
        int res = MAX;
        for(int i = 0;i <= cnt - 1;++i)
        {
             res = min(res,dp[ans[i].x][ans[i].y]);
        }
        if(res != MAX)
            cout << res << endl;
        else
            cout << "Poor ANGEL has to stay in the prison all his life." << endl;

    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章