当时做的时候wa了很多次。。。orz
不知道怎么输出路径,参考网上的代码。。。所以也不是原创
题意:
要求从(0,0)走到(n-1,m-1)所花费的最短时间;
‘.’是可以走的,消耗一个单位的时间,
‘x’是不可以走的,
‘n’代表此处需要消耗n个单位的时间,
分析:
bfs结合优先队列求最短问题。,,,注意细节即可
#include <iostream>
#include <cstdio>
#include <queue>
#include <limits.h>
#include <time.h>
using namespace std;
const int maxn=103;
int N,M;
int dx[4]={-1,0,0,1},dy[4]={0,1,-1,0};
struct node
{
char data;
int x,y,time;
int prx,pry;
friend bool operator<(node a,node b)
{
return a.time>b.time;//<为从大到小排列,>为从小到大排列
}
}step[maxn][maxn];
bool check(int x,int y)//检测是否在范围内
{
if(x>=0&&x<N&&y>=0&&y<M)
return true;
return false;
}
int bfs()
{
priority_queue<node> que;
step[0][0].x=step[0][0].y=step[0][0].time=0;
que.push(step[0][0]);
while(que.size())
{
node cur=que.top();
que.pop();
if(cur.x==N-1&&cur.y==M-1) return 1;
for(int i=0;i<4;i++)
{
int x,y;
x=cur.x+dx[i]; y=cur.y+dy[i];
if(!check(x,y)||step[x][y].data=='X')
continue;
else
{
if(step[x][y].data=='.'&&step[x][y].time>cur.time+1)
{
step[x][y].time=cur.time+1;
step[x][y].prx=cur.x;
step[x][y].pry=cur.y;
que.push(step[x][y]);
}
else if(step[x][y].data>='1'&&step[x][y].data<='9'&&step[x][y].time>cur.time+step[x][y].data-'0'+1)
{
step[x][y].time=cur.time+step[x][y].data-'0'+1;
step[x][y].prx=cur.x;
step[x][y].pry=cur.y;
que.push(step[x][y]);
}
}
}
}
return -1;
}
void print(int x,int y)
{
if(x==0&&y==0) return;
int prx=step[x][y].prx, pry=step[x][y].pry, tend=step[x][y].time;
int tstart=step[prx][pry].time;
print(prx,pry);
printf("%ds:(%d,%d)->(%d,%d)\n",tstart+1,prx,pry,step[x][y].x,step[x][y].y);
for(int i=tstart+2;i<=tend;i++)
{
printf("%ds:FIGHT AT (%d,%d)\n",i,x,y);
}
}
int main()
{
//clock_t start,end;
// start=clock();
// freopen("in.txt","r",stdin);
while(~scanf("%d%d",&N,&M))
{
for(int i=0;i<N;i++)
{
getchar();
for(int j=0;j<M;j++)
{
scanf("%c",&step[i][j].data);
step[i][j].x=i;
step[i][j].y=j;
step[i][j].time=INT_MAX;
}
}
if(bfs()==-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",step[N-1][M-1].time);
print(N-1,M-1);
}
printf("FINISH\n");
}
//end=clock();
//printf("time is %6.3f\n",(double)(end-start));
return 0;
}