题目大意:给定一个N*M的,一个点到相邻的点花费1s的时间,如果到达的点是数字n,又会在该点停留ns;如果该点是‘X’,则无法通过。如果求从(0,0)点到(N-1,M-1)点的最短时间。记录花费最短时间的路径。
做法:直接进行一遍优先队列+bfs,另外用一个数组pre[][]记录当前点的前一个点。当搜索完后,从点(N-1,M-1)开始,将所有的前一个点都保存进栈里面,然后根据题意输出结果。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
const int maxn=105;
int dd[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
char ch[maxn][maxn];
bool vis[maxn][maxn];
int n,m;
struct point
{
int x,y;
};
struct node
{
int x,y;
int t;
bool operator<(const node&a)const
{
return t>a.t;
}
};
point pre[maxn][maxn];
bool check_move(int x,int y)
{
if(x>=0 && x<n && y>=0 && y<m)return true;
else return false;
}
int bfs()
{
priority_queue<node> que;
node st;
st.x=0;
st.y=0;
st.t=0;
que.push(st);
pre[0][0].x=pre[0][0].y=0;
vis[0][0]=true;
while(!que.empty())
{
node now=que.top();
que.pop();
node tmp;
for(int i=0; i<4; i++)
{
tmp.x=now.x+dd[i][0];
tmp.y=now.y+dd[i][1];
tmp.t=now.t;
if(check_move(tmp.x,tmp.y))
{
if(vis[tmp.x][tmp.y])continue;
if(ch[tmp.x][tmp.y]=='X')continue;
pre[tmp.x][tmp.y].x=now.x;
pre[tmp.x][tmp.y].y=now.y;
if(ch[tmp.x][tmp.y]=='.')tmp.t++;
else tmp.t+=ch[tmp.x][tmp.y]-'0'+1;
if(tmp.x==n-1 && tmp.y==m-1)return tmp.t;
que.push(tmp);
vis[tmp.x][tmp.y]=true;
}
}
}
return -1;
}
void solve(int res)
{
stack<point> stk;
point tt1,tt;
tt.x=n-1;
tt.y=m-1;
while(!(tt.x==0 && tt.y==0))
{
stk.push(tt);
tt=pre[tt.x][tt.y];
}
printf("It takes %d seconds to reach the target position, let me show you the way.\n",res);
tt.x=tt.y=0;
int ti=1;
bool flag=false;
while(!stk.empty())
{
tt1=stk.top();
stk.pop();
printf("%ds:(%d,%d)->(%d,%d)\n",ti++,tt.x,tt.y,tt1.x,tt1.y);
if(ch[tt1.x][tt1.y]!='.')
flag=true;
if(flag)
{
int l=ch[tt1.x][tt1.y]-'0';
for(int i=1; i<=l; i++)
printf("%ds:FIGHT AT (%d,%d)\n",ti++,tt1.x,tt1.y);
}
tt=tt1;
}
}
int main()
{
// freopen("in.txt","r",stdin);
while(~scanf("%d%d",&n,&m))
{
for(int i=0; i<n; i++)
scanf("%s",ch[i]);
memset(vis,0,sizeof(vis));
int res=bfs();
if(res!=-1)solve(res);
else printf("God please help our poor hero.\n");
printf("FINISH\n");
}
return 0;
}