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;
}