#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <stack>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=105;
const int INF=1e9;
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
char e[maxn][maxn];
int time[maxn][maxn];
int n,m,t,ans,num;
struct node{
int x,y,step;
}g[maxn][maxn];
void bfs()
{
int i,j,k,xx,yy,step;
queue<node>q;
node u,f;
f.x=f.y=f.step=0;
time[0][0]=0;
q.push(f);
while(!q.empty())
{
f=q.front();
q.pop();
if(f.x==n-1&&f.y==m-1&&f.step<ans)
ans=f.step;
for(i=0;i<4;i++)
{
xx=f.x+dir[i][0];
yy=f.y+dir[i][1];
if(xx<0||yy<0||xx>=n||yy>=m||e[xx][yy]=='X')continue;
if(e[xx][yy]=='.')
step=f.step+1;
else
step=f.step+e[xx][yy]-'0'+1;
if(step<time[xx][yy])
{
time[xx][yy]=step;
g[xx][yy].x=f.x;g[xx][yy].y=f.y;
u.x=xx;u.y=yy;u.step=step;
q.push(u);
}
}
}
}
void print(int a,int b)
{
int i,j;
if(g[a][b].x==0&&g[a][b].y==0)
{
cout<<++num<<"s:(0,0)->("<<a<<","<<b<<")"<<endl;
if(e[a][b]<='9'&&e[a][b]>='0')
{
for(j=0;j<e[a][b]-'0';j++)
cout<<++num<<"s:FIGHT AT ("<<a<<","<<b<<")"<<endl;
}
return;
}
print(g[a][b].x,g[a][b].y);
cout<<++num<<"s:("<<g[a][b].x<<","<<g[a][b].y<<")->("<<a<<","<<b<<")"<<endl;
if(e[a][b]<='9'&&e[a][b]>='0')
{
for(j=0;j<e[a][b]-'0';j++)
cout<<++num<<"s:FIGHT AT ("<<a<<","<<b<<")"<<endl;
}
}
int main()
{
while(cin>>n>>m)
{
int i,j,k,rx,ry,x,y;
for(i=0;i<n;i++)
cin>>e[i];
ans=INF;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
time[i][j]=INF;
bfs();
if(ans==INF)cout<<"God please help our poor hero."<<endl<<"FINISH"<<endl;
else
{
cout<<"It takes "<<ans<<" seconds to reach the target position, let me show you the way."<<endl;
num=0;
print(n-1,m-1);
cout<<"FINISH"<<endl;
}
}
return 0;
}
/*
bfs,
用time[i][j]表示到i,j所需最短的时间,用于剪枝。
用g[i][j]记录到i,j时,使得time[i][j]最小的前驱位置
第一次用dfs写,wa了,测了下,虽然剪枝了,可在最坏情况下复杂度还有7*10^7。。
*/
hdu 1026 Ignatius and the Princess I BFS+剪枝
最新推荐文章于 2018-11-07 14:33:57 发布