您的位置:首页 > 其它

HDU 1026 Ignatius and the Princess I(带路径的BFS)

2016-12-31 13:34 423 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1026

题意:给出一个迷宫,求出到终点的最短时间路径。

这道题目在迷宫上有怪物,不同HP的怪物会损耗不同的时间,这个时候可以用优先队列,每次让时间最短的出队列。由于最后还需要输出路径,所以需要设置一个数组来保存路径。

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

const int maxn = 100 + 5;

struct node
{
int x, y;
int time;
friend bool operator < ( node a, node b)   //重载<号
{
return b.time<a.time;
}
};

char map[maxn][maxn];
int visited[maxn][maxn];
int path[maxn][maxn];
int  n, m;
int d[][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };

int bfs()
{
node q,now;
priority_queue<node> p;
q.x = 0;
q.y = 0;
q.time = 0;
p.push(q);
while (!p.empty())
{
q = p.top();
p.pop();
if (q.x == n - 1 && q.y == m - 1)  return q.time;
for (int i = 0; i < 4; i++)
{
int xx = q.x + d[i][0];
int yy = q.y + d[i][1];
now.x = xx;
now.y = yy;
now.time = q.time;
if (xx >= 0 && xx < n && yy >= 0 && yy < m && map[xx][yy]!='X' && !visited[xx][yy])
{
if (map[xx][yy] == '.')   now.time++;
else now.time =now.time+ (map[xx][yy] - '0'+1);
visited[xx][yy] = 1;
path[xx][yy] = i + 1;     //记录路径
p.push(now);
}
}
}
return -1;
}

int temp;

void print(int x, int y)
{
int xx, yy;
if (path[x][y] == 0)   return;
xx = x - d[path[x][y] - 1][0];   //寻找第一个路径点
yy = y - d[path[x][y] - 1][1];
print(xx, yy);
printf("%ds:(%d,%d)->(%d,%d)\n", temp++, xx, yy, x, y);
if (map[x][y] <= '9' && map[x][y] >= '0')
{
int m = map[x][y] - '0';
while (m--)    printf("%ds:FIGHT AT (%d,%d)\n", temp++, x, y);
}
}

int main()
{
while (cin >> n >> m && (n||m))
{
memset(visited, 0, sizeof(visited));
memset(path, 0, sizeof(path));
for (int i = 0; i < n;i++)
for (int j = 0; j < m; j++)
cin >> map[i][j];
visited[0][0] = 1;
int ans=bfs();
if (ans == -1)  cout << "God please help our poor hero." << endl;
else
{
cout << "It takes " << ans << " seconds to reach the target position, let me show you the way." << endl;
temp = 1;
print(n - 1,m - 1);
}
cout << "FINISH" << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: