#include <bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
int n,m,num;
struct Node{
int x,y;
int time;
int prex,prey;
char c;
bool operator>(const Node & node) const{
return time>node.time;
}
};
Node node[105][105];
int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
bool BFS(){
//queue<Node> pq;
priority_queue<Node,vector<Node>,greater<Node> > pq;
node[0][0].time=0;
pq.push(node[0][0]);
while(!pq.empty()){
Node now=pq.top();
//Node now=pq.front();
pq.pop();
for(int i=0;i<4;i++){
int x=now.x+dir[i][0]; //下一个点
int y=now.y+dir[i][1];
if(x>=0&&x<n&&y>=0&&y<m&&node[x][y].c=='.'){
if(node[x][y].time>now.time+1){
node[x][y].time=now.time+1;
node[x][y].prex=now.x;
node[x][y].prey=now.y;
pq.push(node[x][y]);
//printf("点(%d,%d)压入栈中\n",node[x][y].x,node[x][y].y);
}
}else if(x>=0&&x<n&&y>=0&&y<m&&node[x][y].c>='0'&&node[x][y].c<='9'){
if(node[x][y].time>now.time+node[x][y].c-'0'+1){
node[x][y].time=now.time+node[x][y].c-'0'+1;
node[x][y].prex=now.x;
node[x][y].prey=now.y;
pq.push(node[x][y]);
//printf("点(%d,%d)压入栈中\n",node[x][y].x,node[x][y].y);
}
}
//cout<<x<<y<<endl;
if(x==n-1&&y==m-1)
return true;
}
}
return false;
}
void print_result(int i,int j){
if(i==0&&j==0)
return;
int px=node[i][j].prex;//前一点坐标
int py=node[i][j].prey;
print_result(px,py);
printf("%ds:(%d,%d)->(%d,%d)\n",node[px][py].time+1,node[px][py].x,node[px][py].y,node[i][j].x,node[i][j].y);
if(node[i][j].c>='0'&&node[i][j].c<='9'){
for(int tmp=node[px][py].time+2;tmp<node[px][py].time+2+node[i][j].c-'0';tmp++){
printf("%ds:FIGHT AT (%d,%d)\n",tmp,node[i][j].x,node[i][j].y);
}
}
}
int main(){
while(~scanf("%d%d",&n,&m)){
getchar();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%c",&node[i][j].c);
node[i][j].x=i;node[i][j].y=j;
node[i][j].time=inf;
}
getchar();
}
bool state=false;
state=BFS();
if(!state){
printf("God please help our poor hero.\n");
}else{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",node[n-1][m-1].time);
print_result(n-1,m-1);
}
printf("FINISH\n");
}
return 0;
}
hdu 1026 Ignatius and the Princess I(优先队列+bfs)
最新推荐文章于 2024-07-14 13:39:50 发布