天啦噜,第一个广搜题,还是先看了别人的思路。
才写的。我这个写的还算思路明白,队列。打印用地递归。用栈也行。如果数据太多的话用vetor。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<queue>
#define INF 99999999;
using namespace std;
int n,m;
struct node{
int x,y,hp,step;
char ch;
bool chack(){
if(x<0||x>n-1||y<0||y>m-1)return false;
return true;
}
}s,d,v,e,go[105][105],w[105][105];
int vis[105][105],flag,c;
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int bfs(){
queue<node> que;
memset(vis,0,sizeof(vis));
go[0][0].step=0;
que.push(go[0][0]);
vis[0][0]=1;
while(!que.empty()){
d=que.front();
que.pop();
v=d;
while(vis[d.x][d.y]>1){
vis[d.x][d.y]--;
d=que.front();
que.pop();
}
vis[d.x][d.y]=0;
for(int i=0;i<4;i++){
v.x=d.x+dir[i][0];
v.y=d.y+dir[i][1];
if(v.chack()&&go[v.x][v.y].ch!='X'&&d.step+1+d.hp<go[v.x][v.y].step+go[v.x][v.y].hp){
w[v.x][v.y].x=d.x;w[v.x][v.y].y=d.y;//printf("%d %d %d %d\n",w[v.x][v.y].x,w[v.x][v.y].y,d.x,d.y);
go[v.x][v.y].step=d.step+1+d.hp;
que.push(go[v.x][v.y]);
vis[v.x][v.y]++;
}
}
}
if(go[n-1][m-1].step!=99999999){
flag=0;
}
}
void way(int a,int b)
{
if(w[a][b].x==a && w[a][b].y==b)
{
while(go[a][b].hp--)
printf("%ds:FIGHT AT (%d,%d)\n",c++,a,b);
return ;
}
way(w[a][b].x,w[a][b].y);
printf("%ds:(%d,%d)->(%d,%d)\n",c++,w[a][b].x,w[a][b].y,a,b);
while(go[a][b].hp--)
printf("%ds:FIGHT AT (%d,%d)\n",c++,a,b);
}
int main(){
while(~scanf("%d%d",&n,&m)){
for(int i=0;i<n;i++){
getchar();
for(int j=0;j<m;j++){
scanf("%c",&go[i][j].ch);
if(isdigit(go[i][j].ch)) go[i][j].hp=go[i][j].ch-'0';
else go[i][j].hp=0;
go[i][j].step=INF;
go[i][j].x=i,go[i][j].y=j;
w[i][j].x=i,w[i][j].y=j;
}
}
flag=1,c=1;
bfs();
if(flag)
cout<<"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",go[n-1][m-1].hp + go[n-1][m-1].step);
c = 1;
way(n-1,m-1);
cout<<"FINISH\n";
}
//for(int i=0;i<n;i++){for(int j=0;j<m;j++)printf("(%d,%d)->%d ",w[i][j].x,w[i][j].y,go[i][j].step);printf("\n");}
}
}
----------
“`