來源:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1649
http://acm.hdu.edu.cn/showproblem.php?pid=1242
本題並不是簡單地bfs,需要注意以下問題:
1、幹掉一個門衛也需要1個單位的時間,也就是說要跳到‘x'個需要兩個單位的時間,所以路徑最短;
2、天使人緣好,朋友不一定只有1個。
我採用的方法是在bfs的基礎上,一旦遇到’x',先把它的上一節點再進一次隊,然後再訪問一次‘x'。
不過在參考題解之後得知原來還有更好的方法,就是使用優先隊列。
代碼:
#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int main()
{
int x, y, x1, y1, n, m, i, j, vis[200][200], map[200][200],vx[200],vy[200];
int dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 };
char ch[200][200];
while (cin >> n >> m)
{
queue<int>q;
memset(vis, 0, sizeof(vis));
memset(map, 0, sizeof(map));
for (i = 0; i<n; i++)
for (j = 0; j<m; j++)
{
cin >> ch[i][j];
if (ch[i][j] == 'r')
{
q.push(i); q.push(j);
vis[i][j] = 1;
}
}
while (!q.empty())
{
x = q.front(); q.pop();
y = q.front(); q.pop();
if (ch[x][y] == 'a') break;
for (i = 0; i<4; i++)
{
x1 = x + dx[i];
y1 = y + dy[i];
if (x1 >= 0 && x1<n&&y1 >= 0 && y1<m&&ch[x1][y1] != '#')
{
if (vis[x1][y1] == 0 && (ch[x1][y1] == '.' || ch[x1][y1] == 'a'))
{
q.push(x1);
q.push(y1);
map[x1][y1] = map[x][y] + 1;
vis[x1][y1] = 1;
}
if (vis[x1][y1] == 0 && ch[x1][y1] == 'x')
{
vx[x1] = x;
vy[y1] = y;
vis[x1][y1] = 2;
q.push(x);
q.push(y);
}
else if (vis[x1][y1] == 2 && (ch[x1][y1] == 'x') &&vx[x1]==x&&vy[y1]==y )
{
q.push(x1);
q.push(y1);
map[x1][y1]=map[x][y]+2;
vis[x1][y1] = 4;
}
}
}
}
if (ch[x][y] != 'a') cout << "Poor ANGEL has to stay in the prison all his life." << endl;
else cout << map[x][y] << endl;
}
return 0;
}
以上程序我沒有采用優先隊列,在hdoj上評測通過了,但是在zoj上試了n遍都無法通過,可能是算法本身有問題吧,由於時間問題,我也暫且擱着了。