给你一个图,图上存在一些monster,每一次打死一个怪,要消耗一定的时间值。求最短时间到达终点!很简答的一个宽搜题。由于打怪耗时,所以采用延迟搜索!题目的关键是要输出路径,采用dfs深度优先!http://acm.hdu.edu.cn/showproblem.php?pid=1026
#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
#define N 101
using namespace std;
int map[N][N],f[N][N];
bool v[N][N];
int jump[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int n,m,res,ks;
struct node
{
int x,y,s;
}q,p,pre[N][N];
void init()
{
int i,j;
char c;
res=-1;ks=1;
memset(map,0,sizeof(map));
memset(f,0,sizeof(f));
for(i=0;i<n;i++)
{
getchar();
for(j=0;j<m;j++)
{
scanf("%c",&c);
if(c=='.') map[i][j]=-1;
else if(c=='X') map[i][j]=0;
else map[i][j]=c-48;
f[i][j]=map[i][j];
}
}
memset(v,0,sizeof(v));
memset(pre,0,sizeof(pre));
}
int is_b(node p)
{
if(p.x<0 || p.y<0 || p.x>=n || p.y>=m
||map[p.x][p.y]==0 || v[p.x][p.y])
return 1;
return 0;
}
void bfs()
{
int i;
queue< node > que;
q.x=q.y=q.s=0;
v[0][0]=1;
map[0][0]=0;
if(f[0][0]>=1) q.s=f[0][0];
//考虑起点有怪
que.push(q);
while(!que.empty())
{
q=que.front();que.pop();
if(q.x==n-1 && q.y==m-1 && map[q.x][q.y]==-1)
{
res=q.s;
//时间ok
return;
}
if(map[q.x][q.y]>=1)
{
++q.s;
if(map[q.x][q.y]==1) map[q.x][q.y]=-1;
else map[q.x][q.y]-=1;
que.push(q);
}
else
{
for(i=0;i<4;i++)
{
p.x=q.x+jump[i][0];
p.y=q.y+jump[i][1];
p.s=q.s+1;
if(is_b(p)) continue;
v[p.x][p.y]=1;
pre[p.x][p.y].x=q.x;
pre[p.x][p.y].y=q.y;
que.push(p);
}
}
}
}
void dfs(int x1,int y1)
{
if(x1==0 && y1==0) return;
dfs(pre[x1][y1].x , pre[x1][y1].y);
int w=pre[x1][y1].x,e=pre[x1][y1].y;
if(f[w][e]>=1)
{
for(int i=1;i<=f[w][e];i++)
{
printf("%ds:FIGHT AT (%d,%d)\n",ks++,w,e);
}
}
printf("%ds:(%d,%d)->(%d,%d)\n",ks++,w,e,x1,y1);
}
void output()
{ //测试函数
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
printf("%d",f[i][j]);
puts("");
}
}
int main ()
{
//freopen("k.txt","r",stdin);
int i;
while(~scanf("%d%d",&n,&m))
{
init();
//output();
bfs();
if(res==-1)
{
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",res);
dfs(n-1,m-1);
if(f[n-1][m-1]>=1)
{
for(i=0;i<f[n-1][m-1];i++)
printf("%ds:FIGHT AT (%d,%d)\n",ks++,n-1,m-1);
}
}
printf("FINISH\n");
}
return 0;
}