分析:就是优先队列+bfs
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 110;
int fight[maxn][maxn];
int n, m;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
struct node
{
int x, y, time;
friend bool operator < (node a, node b)//time小的优先级高;
{
return a.time > b.time;
}
};
struct fff
{
int x, y;
char c;
}map[maxn][maxn];
int bfs()
{
priority_queue<node>q;//优先队列;
//queue<node>q;
node temp, type;
while(!q.empty())//清空 要不要无所谓;
{
q.pop();
}
temp.x = n-1;//从目标开始 到 (0, 0)
temp.y = m-1;
if(map[n-1][m-1].c >= '1' && map[n-1][m-1].c <= '9')//记录打怪用的时间;
{
temp.time = map[n-1][m-1].c - '0';
fight[n-1][m-1] = map[n-1][m-1].c - '0';
}
else
temp.time = 0;
map[n-1][m-1].c = 'X';
q.push(temp);//压入队列;
while(!q.empty())
{
temp=q.top();//去队列的第一个;
q.pop();//去队列的第一个;
if(temp.x == 0 && temp.y == 0)//满足条件;
return temp.time;
type = temp;
for(int i = 0; i < 4; i++)
{
int fx = type.x = temp.x + dir[i][0];
int fy = type.y = temp.y + dir[i][1];
if(fx >= 0 && fx < n && fy >= 0 && fy < m && map[fx][fy].c != 'X')
{
if(map[fx][fy].c >= '1' && map[fx][fy].c <= '9')
{
fight[fx][fy] = map[fx][fy].c - '0';
type.time = temp.time + map[fx][fy].c - '0' + 1;
}
else
type.time = temp.time + 1;
q.push(type);//压入队列;
map[fx][fy].c = 'X';
map[fx][fy].x = temp.x;
map[fx][fy].y = temp.y;
}
}
}
return -1;
}
int main()
{
while(scanf("%d%d", &n, &m) != EOF)
{
getchar();
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
scanf("%c", &map[i][j].c);//记录地图;
}
getchar();
}
memset(fight, 0, sizeof(fight));//初始化,
int f = bfs();
if(f != -1)
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",f);
int sec = 1, x = 0, y = 0;
while(sec != f+1)
{
printf("%ds:(%d,%d)->(%d,%d)\n", sec++, x, y, map[x][y].x, map[x][y].y);
for(int i = 0; i < fight[map[x][y].x][map[x][y].y]; i++)
printf("%ds:FIGHT AT (%d,%d)\n", sec++, map[x][y].x, map[x][y].y);
int tx = map[x][y].x;
int ty = map[x][y].y;
x = tx;
y = ty;
}
}
else
printf("God please help our poor hero.\n");
printf("FINISH\n");
}
}
hdu1026
最新推荐文章于 2018-10-06 14:56:14 发布