題意:給一個n*m的圖,圖中有X,有.有數字,x代表牆,.代表路,數字代表當走到這個地方的時候,還要停留多少
秒,問你從左上角到右下角的最少時間是多少。當能走通的時候,要把路徑打印出來。
除了Map數組和標記數組之外,還應該有一個結構體數組存放當前點是由那個點廣搜過來的
*/
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
char Map[105][105];//存圖
int Map1[105][105]/*標記數組*/,bu[4][2]={0,1,0,-1,1,0,-1,0},n,m;
struct node
{
int x,y,temp;
friend bool operator <(node p,node q)
{
return p.temp>q.temp;
}
}S,D;
node MM[105][105];//結構體數組存放該點是由那個點廣搜過來的
int bfs()
{
memset(Map1,0,sizeof(Map1));
priority_queue<node> v;
while(!v.empty())
v.pop();
node l,r;
int i;
v.push(S);
Map1[S.x][S.y]=1;
while(!v.empty())
{
l=v.top();
//printf("++++%d %d %d\n",l.x,l.y,l.temp);
v.pop();
if(l.x==D.x&&l.y==D.y)
return l.temp;
for(i=0;i<4;i++)
{
int aa=l.x+bu[i][0];
int bb=l.y+bu[i][1];
if(aa>=0&&aa<n&&bb>=0&&bb<m&&Map1[aa][bb]==0&&Map[aa][bb]!='X')
{
Map1[aa][bb]=1;
MM[aa][bb].x=l.x;MM[aa][bb].y=l.y;
r.x=aa;r.y=bb;
if(Map[aa][bb]=='.')
r.temp=l.temp+1;
else
r.temp=l.temp+Map[aa][bb]-'0'+1;
//printf("%d %d %d\n",r.x,r.y,r.temp);
v.push(r);
}
}
}
return -1;
}
void Printf(int aa,int nn,int mm)//通過遞歸輸出圖
{
if(aa==1)//當aa是1秒的時候開始輸出
{
printf("%ds:(%d,%d)->(%d,%d)\n",aa,MM[nn][mm].x,MM[nn][mm].y,nn,mm);
return ;
}
else
{
if(Map[nn][mm]>'0'&&Map[nn][mm]<='9')//當時數字的時候輸出這麼多次
{
Map[nn][mm]-=1;//圖中的數字減1
Printf(aa-1,nn,mm);//先遞歸,當遞歸回來時在輸出圖
printf("%ds:FIGHT AT (%d,%d)\n",aa,nn,mm);//輸出圖
}
else
{
Printf(aa-1,MM[nn][mm].x,MM[nn][mm].y);//當圖中是點的時候先遞歸後輸出圖
printf("%ds:(%d,%d)->(%d,%d)\n",aa,MM[nn][mm].x,MM[nn][mm].y,nn,mm);//輸出圖
}
}
}
int main()
{
int i;
S.x=0;S.y=0;
while(scanf("%d%d",&n,&m)!=EOF)
{
D.x=n-1;D.y=m-1;
for(i=0;i<n;i++)
scanf("%s",Map[i]);
int aa=bfs();
if(aa==-1)
{
printf("God please help our poor hero.\nFINISH\n");
}
else
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",aa);
Printf(aa,n-1,m-1);//輸出圖的函數
printf("FINISH\n");
}
}
return 0;
}