HDU1026 BFS&&优先队列&&路径保存


刚开始做BFS专题时遇到它,因为路径保存放弃了


现在做,刚开始各种WA。。。。。


后来加了个优先队列,就AC了。。额。。

#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<map>
#include<cmath>
#include<iostream>
#include <queue>
#include <stack>
#include<algorithm>
#include<set>
using namespace std;
#define inf 2147483647
#define eps 1e-8
#define LL long long
#define M 50005					
#define mol 1000000007
int mov[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct node
{
   int x,y,step;
   friend bool operator<(node a,node b)
   {
       return a.step>b.step;
   };
};
int n,m,vis[105][105];
char s[105][105];
int pd(int x,int y)
{
   if(x>=0&&x<n&&y>=0&&y<m&&s[x][y]!='X')
	   return 1;
   return 0;
}
struct dire
{
   int x,y;
   
}f[101][101];//保存当前点的前一点的位置
void bfs()
{
   priority_queue<node>Q;
   int ans=0,k,dx,dy;
   f[n-1][m-1].x=-1;//终点标志
   vis[n-1][m-1]=1;
   node p,q;
   p.x=n-1;
   p.y =m-1;
   p.step =0;
   if(s[n-1][m-1]!='.')
	   p.step =s[n-1][m-1]-'0';
   Q.push(p);
   while(!Q.empty())
   {
       p=Q.top ();
	   Q.pop();
	   if(p.x==0&&p.y==0)
	   {
		   printf("It takes %d seconds to reach the target position, let me show you the way.\n",p.step);
           k=1;
		   int a=p.x;//当前点
		   int b=p.y;
		   while(f[a][b].x!=-1)
		   {
		      int c=f[a][b].x;//当前点的前一点
			  int d=f[a][b].y;
			  printf("%ds:(%d,%d)->(%d,%d)\n",k++,a,b,c,d);
			  if(s[c][d]!='.')
			  {
			     for(int l=0;l<s[c][d]-'0';l++)
					 printf("%ds:FIGHT AT (%d,%d)\n",k++,c,d);
			  }
			  a=c;
			  b=d;
		   }
		   printf("FINISH\n");
		   return;
	   }
	   q=p;
	   for(int i=0;i<4;i++)
	   {
	      dx =q.x +mov[i][0];
		  dy =q.y+mov[i][1];
		  if(vis[dx][dy]==0&&pd(dx,dy))
		  {
		      vis[dx][dy]=1;
			  p.x=dx;p.y=dy;
			  
			  if(s[dx ][dy]!='.')
				  p.step =q.step +s[dx][dy]-'0'+1;
			  else
				  p.step =q.step +1;
			f[dx][dy].x=q.x;//路径保存
			f[dx][dy].y=q.y;
			  Q.push(p);
		  }
	   }
   }
   printf("God please help our poor hero.\nFINISH\n");
   
}
int main()
{
	while(~scanf("%d%d",&n,&m))
	{
	   int i,j;
	   memset(vis,0,sizeof(vis));
	   memset(f,0,sizeof(f));
	   for(i=0;i<n;i++)
	   {
	       scanf("%s",s[i]);
	   }
	   bfs();
	}
return 0;
}


你可能感兴趣的:(HDU1026 BFS&&优先队列&&路径保存)