標籤:bfs
簡單bfs問題。
迷宮左上方是入口,右下角是出口,迷宮中有戰鬥力為1~9的守衛,打敗他們需要1~9的時間。
遇到怪物判一下就可以了。步驟倒序輸出即可。
由於需要記錄步驟,不適用STL的queue。
#include<cstdio>#include<cstring>#include<string>#include<queue>#include<algorithm>#include<map>#include<stack>#include<iostream>#include<list>#include<set>#include<vector>#include<cmath>#define INF 0x7fffffff#define eps 1e-8#define LL long long#define PI 3.141592654#define CLR(a,b) memset(a,b,sizeof(a))#define FOR(i,a,n) for(int i= a;i< n ;i++)#define debug puts("==fuck==")#define acfun std::ios::sync_with_stdio(false)#define SIZE 1000+10using namespace std;int xx[]={0,0,-1,1};int yy[]={-1,1,0,0};int n,m;char g[101][101];struct lx{ int x,y,lv,path; void init(int xx,int yy,int llv,int p) { x=xx,y=yy,lv=llv,path=p; }};lx q[10000001];void bfs(){ bool vis[101][101]; CLR(vis,0); vis[0][0]=1; lx tmp; tmp.init(0,0,0,-1); int h=0,e=0; q[h++]=tmp; bool flag=0; while(e<h) { tmp=q[e++]; lx now;// printf("%d %d ==%d\n",tmp.x,tmp.y,tmp.lv);// system("pause"); if(tmp.x==n-1&&tmp.y==m-1&&(g[tmp.x][tmp.y]<'1'||g[tmp.x][tmp.y]>'9')) { flag=1; break; } if(g[tmp.x][tmp.y]>='1'&&g[tmp.x][tmp.y]<='9') { now.init(tmp.x,tmp.y,tmp.lv+1,e-1); g[tmp.x][tmp.y]--; vis[tmp.x][tmp.y]=1; q[h++]=now; } else FOR(k,0,4) { int x=tmp.x+xx[k]; int y=tmp.y+yy[k]; if(x<0||y<0||x>=n||y>=m||vis[x][y]||g[x][y]=='X') continue; now.init(x,y,tmp.lv+1,e-1); vis[x][y]=1; q[h++]=now; } } if(flag) { stack<lx>out; out.push(tmp); int path=tmp.path; int t=tmp.lv; while(path!=-1) { out.push(q[path]); path=q[path].path; } printf("It takes %d seconds to reach the target position, let me show you the way.\n",t); while(!out.empty()) { lx now=out.top();out.pop(); if(now.lv==0) { tmp=now; continue; } if(now.x==tmp.x&&now.y==tmp.y) printf("%ds:FIGHT AT (%d,%d)\n",now.lv,now.x,now.y); else printf("%ds:(%d,%d)->(%d,%d)\n",now.lv,tmp.x,tmp.y,now.x,now.y); tmp=now; } } else puts("God please help our poor hero."); puts("FINISH");}int main(){ while(~scanf("%d%d",&n,&m)) { char str[101]; FOR(i,0,n) { scanf("%s",str); FOR(j,0,m) g[i][j]=str[j]; } bfs(); }}
HDU 1026 Ignatius and the Princess I