题目地址:点击打开链接
题意:小明要从一个矩阵的(0,0)点到(n-1,m-1)点问最少花费多少时间到达,
. : The place where Ignatius can walk on.
X : The place is a trap, Ignatius should not walk on it.
n : Here is a monster with n HP(1<=n<=9), if Ignatius walk on it, it takes him n seconds to kill the monster.
思路:参考大神A的,学到几个技巧,刚开始把图转化为int类型,在后面不用每次判断,还有一点是这个和普通的BFS搜索题有点不同,一个人可以在一个点呆好几秒,这样必须就得用到优先队列,不然按出栈顺序到达的有可能不是最短的时间,还有就是判断条件一定要写清,因为这个wrong了几发,还有就是程序不能用next标记变量或数组,会导致编译错误,注意一下
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
typedef long long ll;
using namespace std;
int n,m,temp;
int map1[110][110];
int visit[110][110];
int pre[110][110];
char a[110];
struct node
{
int x,y;
int step;
friend bool operator < (node a,node b)
{
return a.step > b.step;//最小值优先
}
}now,future;
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
bool judge(int x,int y)
{
if(x >= 0 && x < n && y >= 0 && y < m && !visit[x][y] && map1[x][y] != -1)//<n和<m加了等号,wrong了几发,太粗心了
return true;
return false;
}
int bfs()
{
int i;
priority_queue<node> pq;
now.x = 0;
now.y = 0;
now.step = 0;
visit[0][0] = 1;
pq.push(now);
while(!pq.empty())
{
future = pq.top();
pq.pop();
if(future.x == n-1 && future.y == m-1)
return future.step;
for(i=0; i<4; i++)
{
now.x = future.x + dir[i][0];
now.y = future.y + dir[i][1];
if(judge(now.x,now.y))
{
visit[now.x][now.y] = 1;
now.step = future.step + 1 + map1[now.x][now.y];
pre[now.x][now.y] = i;
pq.push(now);
}
}
}
return -1;
}
void shuchu(int x,int y)
{
if(pre[x][y] == -1)
return;
int newx = x - dir[pre[x][y]][0];
int newy = y - dir[pre[x][y]][1];
shuchu(newx,newy);
printf("%ds:(%d,%d)->(%d,%d)\n",temp++,newx,newy,x,y);
while(map1[x][y] > 0)
{
map1[x][y]--;
printf("%ds:FIGHT AT (%d,%d)\n",temp++,x,y);
}
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&m) != EOF)
{
memset(pre,-1,sizeof(pre));
memset(visit,0,sizeof(visit));
getchar();
for(i=0; i<n; i++)
{
gets(a);
for(j=0; j<m; j++)
{
if(a[j] == '.')
{
map1[i][j] = 0;
}
else if(a[j] == 'X')
{
map1[i][j] = -1;
}
else if(a[j] >= '0' && a[j] <= '9')
{
map1[i][j] = a[j] - '0';
}
}
}
int x = bfs();
if(x == -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",x);
temp = 1;
shuchu(n-1,m-1);
}
printf("FINISH\n");
}
return 0;
}