分析:在BFS中使用优先队列即可获取最小值。
#include<iostream>
#include<queue>
using namespace std; //BFS+优先队列(打印路径)
#define N 101
struct Node //节点
{
int x,y,time;
friend bool operator<(const Node& a,const Node& b) //有限队列根据时间做依据
{
return a.time>b.time; //最小值优先
}
};
struct Path //路径
{
int x,y,time;
} path[N][N];
char map[N][N];
int dir[4][2]={-1,0,0,1,1,0,0,-1};
bool ok(int x,int y,int r,int c)
{
return x>=0&&x<r&&y>=0&&y<c;
}
bool bfs(int x,int y,int r,int c,int* t) //当前坐标x,y,行,列,最短时间
{
int i;
Node u,v;
priority_queue<Node> q;
u.x=x; //初始
u.y=y;
u.time=0;
q.push(u);
path[x][y].x=-1; //起点无前驱
path[x][y].y=-1;
path[x][y].time=0;
while(!q.empty())
{
u=q.top();
q.pop();
if(u.x==r-1 && u.y==c-1) //目的地
{
*t=u.time;
return true;
}
for(i=0;i<4;i++)
{
v.x=u.x+dir[i][0];
v.y=u.y+dir[i][1];
if(ok(v.x,v.y,r,c))
if(map[v.x][v.y]=='.') //可以经过
{
v.time=u.time+1;
q.push(v);
path[v.x][v.y].x=u.x; //记录前驱
path[v.x][v.y].y=u.y;
path[v.x][v.y].time=0;
map[v.x][v.y]='X'; //访问过就不能在访问了
}
else if(map[v.x][v.y]!='X')
{
v.time=u.time+(map[v.x][v.y]-'0')+1; //打怪时间加经过时间
q.push(v);
path[v.x][v.y].x=u.x; //记录前驱
path[v.x][v.y].y=u.y;
path[v.x][v.y].time=map[v.x][v.y]-'0';
map[v.x][v.y]='X'; //访问过就不能在访问了
}
}
}
return false;
}
void PutAns(int t,int x,int y) //时间,终点x,y
{
if(t>0)
if(path[x][y].time--!=0)
{
PutAns(t-1,x,y);
printf("%ds:FIGHT AT (%d,%d)\n",t--,x,y);
}
else
{
PutAns(t-1,path[x][y].x,path[x][y].y);
printf("%ds:(%d,%d)->(%d,%d)\n", t--, path[x][y].x, path[x][y].y, x, y);
}
}
int main()
{
int n,m;
int i,t;
while(scanf("%d%d",&n,&m)==2)
{
for(i=0;i<n;i++)
scanf("%s",map[i]);
t=0;
if(bfs(0,0,n,m,&t))
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n", t);
PutAns(t,n-1,m-1);
}
else
printf("God please help our poor hero.\n");
printf("FINISH\n");
}
return 0;
}
HDU ACM 1026 Ignatius and the Princess I -> BFS+优先队列+路径打印
原文地址:http://blog.csdn.net/a809146548/article/details/46383351