模板题。
代码:
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int n,m;
char s[105][105];
int v[105][105];
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
struct path{
int x,y;
};
struct node{
int x,y;
int step;
queue<path> pa;
};
node ans;
void input()
{
for(int i = 0;i < n;++i)
scanf("%s",s[i]);
}
void output(int f)
{
if(f == -1)
printf("God please help our poor hero.\n");
else
{
path fir,las;
int cnt = 1;
fir = ans.pa.front();
ans.pa.pop();
las = ans.pa.front();
ans.pa.pop();
printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans.step);
printf("%ds:(%d,%d)->(%d,%d)\n",cnt++,fir.x,fir.y,las.x,las.y);
while(!ans.pa.empty())
{
if(s[las.x][las.y] != '.' && s[las.x][las.y] != 'X')
{
int t = s[las.x][las.y] - '0';
while(t--)
{
printf("%ds:FIGHT AT (%d,%d)\n",cnt++,las.x,las.y);
}
}
fir = las;
las = ans.pa.front();
ans.pa.pop();
printf("%ds:(%d,%d)->(%d,%d)\n",cnt++,fir.x,fir.y,las.x,las.y);
}
if(s[las.x][las.y] != '.')
{
int t = s[las.x][las.y] - '0';
while(t--)
{
printf("%ds:FIGHT AT (%d,%d)\n",cnt++,las.x,las.y);
}
}
}
printf("FINISH\n");
}
struct cmp{
bool operator()(node x,node y)
{
return x.step > y.step;
}
};
int bfs()
{
memset(v,0,sizeof(v));
priority_queue<node,vector<node>,cmp> q;
node f,t;
path p;
p.x = 0;
p.y = 0;
f.x = 0;
f.y = 0;
f.step = 0;
f.pa.push(p);
q.push(f);
v[0][0] = 1;
while(!q.empty())
{
node h = q.top();
q.pop();
if(h.x == n - 1 && h.y == m - 1)
{
ans = h;
return 1;
}
for(int i = 0;i < 4;++i)
{
t.x = h.x + dx[i];
t.y = h.y + dy[i];
if(t.x >= 0 && t.x < n && t.y >= 0 && t.y < m && !v[t.x][t.y] && s[t.x][t.y] != 'X')
{
//printf("%d %d\n",t.x,t.y);
if(s[t.x][t.y] == '.')
{
t.step = h.step + 1;
p.x = t.x;
p.y = t.y;
t.pa = h.pa;
t.pa.push(p);
q.push(t);
v[t.x][t.y] = 1;
}
else
{
int time = s[t.x][t.y] - '0';
t.step = h.step + time + 1;
p.x = t.x;
p.y = t.y;
t.pa = h.pa;
t.pa.push(p);
q.push(t);
v[t.x][t.y] = 1;
}
}
}
}
return -1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
input();
int flag = bfs();
output(flag);
}
}