题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3345
题中Y 为起点,E为士兵,若到士兵的上下左右任一位置则不能再走下一步,走入’.’ 和 ‘P’都要消耗1 MV ,’T’要消耗2 MV,’R’要消耗3MV,’#’为墙,不能通过。
题目就是给你一张N*M的图和你拥有的MV数量,让你把所有能走到的点都变为‘*’,‘P’除外。
就是有点像BFS不过因为不同种类的格子消耗的MV不同,所以不能像BFS一样直接把访问过的点标记后不再访问,当重新走到这一个点的时候且剩余的MV大于之前其他路径到达的,则更新该点的数据,并把该点加入搜索的队列中,就是SPFA了。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int t,n,m,v,sh,sl,dir[4][2]={0,1,1,0,0,-1,-1,0},pow[111][111];
int cost[300];
char mp[111][111];
struct node
{
int h,l;
node(int a,int b)
{
h = a;
l = b;
}
};
void spfa()
{
node s(sh,sl);
queue<node>q;
q.push(s);
while(!q.empty())
{
s = q.front();
q.pop();
for(int i=0;i<4;i++)
{
int h = s.h + dir[i][0];
int l = s.l + dir[i][1];
if(h<0||h>=n||l<0||l>=m||mp[h][l]=='#'||mp[h][l]=='E')
continue;
if(pow[s.h][s.l]-cost[mp[h][l]] > pow[h][l])
{
pow[h][l] = pow[s.h][s.l]-cost[mp[h][l]];
int flag = 1;
for(int j=0;j<4;j++)//判断四周是否有‘E’
{
int hh = h + dir[j][0];
int ll = l + dir[j][1];
if(hh<0||hh>=n||ll<0||ll>=m)
continue;
if(mp[hh][ll]=='E')
flag = 0;
}
if(flag)
q.push(node(h,l));
}
}
}
}
int main()
{
cost['.'] = cost['P'] = 1,cost['T'] = 2,cost['R'] = 3;
scanf("%d",&t);
while(t--)
{
memset(pow,-1,sizeof pow);
scanf("%d%d%d",&n,&m,&v);
for(int i=0;i<n;i++)
scanf("%s",mp[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mp[i][j]=='Y')
sh = i,sl = j;
}
}
pow[sh][sl] = v;
spfa();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(pow[i][j]>=0&&mp[i][j]!='Y'&&mp[i][j]!='P')
printf("*");
else
printf("%c",mp[i][j]);
}
printf("\n");
}
printf("\n");
}
return 0;
}