HDU-1026-Ignatius and the Princess I

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=1026

这题是个好题,这题是我做的第一个搜索要求输出路径的,  没有想出来,

解析:

优先队列+bfs+链表式找前一个点,要用到栈(stack)。

运用优先队列来选取当前时间(ans)最少那个点,并且用f[][]数组记录前一个点和当前点(这里相当与链表)。

再运用栈从n-1,m-1开始存入,利用f[][],找到但前点的前一个点。知道找到第一步为止。由于栈是先进后出,

就可以输出他的路径了。

代码

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;

char map[110][110];
int vis[110][110];
int success,n,m,ans;
int dx[4]={1,0,-1,0};
int dy[4]={0,-1,0,1};

struct node
{
int x,y,cnt;
node(int _x=0,int _y=0,int _cnt=0 ):x(_x),y(_y),cnt(_cnt) {};//后面好打包。
friend bool operator <(const node &a,const node &b)
{
return a.cnt >b.cnt;//花时间少的优先。
}
};

node f[110][110];

void bfs()
{
node s;
priority_queue<node> q1;
while(q1.size())
q1.pop();
s.x=0; s.y=0; s.cnt=0;
q1.push(s);
vis[0][0]=1;
while(q1.size())
{
s=q1.top();
q1.pop();
if(s.x==n-1&&s.y==m-1)
{
success=1;
ans=s.cnt;
return ;
}
int i,j,k;
for(k=0;k<4;k++)
{
i=s.x+dx[k]; j=s.y+dy[k];
if(i>=0&&i<n&&j>=0&&j<m&&!vis[i][j]&&map[i][j]!='X')
{
vis[i][j]=1;
f[i][j].x=s.x; f[i][j].y=s.y;//记录前驱;
if(map[i][j]=='.')
q1.push(node(i,j,s.cnt+1));
else
q1.push(node(i,j,s.cnt+map[i][j]-'0'+1));
}
}
}
}

void print()
{
stack<node> q2;
while(q2.size())
q2.pop();
node temp=f[n-1][m-1];
q2.push(node(n-1,m-1,ans));//这里的ans没有任何用,可为ans,也可为其他。主要为了满足node的格式。
while(temp.x>0||temp.y>0)
{
q2.push(temp);
temp=f[temp.x][temp.y];
}
int t=1;
while(q2.size())
{
temp=q2.top();
q2.pop();
if(map[temp.x][temp.y]=='.')
{
printf("%ds:(%d,%d)->(%d,%d) ",t++,f[temp.x][temp.y].x,f[temp.x][temp.y].y,temp.x,temp.y);
}
else
{
printf("%ds:(%d,%d)->(%d,%d) ",t++,f[temp.x][temp.y].x,f[temp.x][temp.y].y,temp.x,temp.y);
int k=map[temp.x][temp.y]-'0';
while(k--)
{
printf("%ds:FIGHT AT (%d,%d) ",t++,temp.x,temp.y);
}
}
}
printf("FINISH ");
return ;
}

int main(void)
{
int i,j;
while(scanf("%d%d",&n,&m)==2)
{
getchar();
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%c",&map[i][j]);
}
getchar();
}
success=0;
memset(vis,0,sizeof(vis));
bfs();
if(success)
printf("It takes %d seconds to reach the target position, let me show you the way. ",ans);
else
{
printf("God please help our poor hero. FINISH ");
continue;
}
print();
}
return 0;
}

原文地址:https://www.cnblogs.com/liudehao/p/4131772.html