Description
What we are discussing is a simple edition of this game. Given a map that consists of empty spaces, rivers, steel walls and brick walls only. Your task is to get a bonus as soon as possible suppose that no enemies will disturb you (See the following picture).
Your tank can't move through rivers or walls, but it can destroy brick walls by shooting. A brick wall will be turned into empty spaces when you hit it, however, if your shot hit a steel wall, there will be no damage to the wall. In each of your turns, you can choose to move to a neighboring (4 directions, not 8) empty space, or shoot in one of the four directions without a move. The shot will go ahead in that direction, until it go out of the map or hit a wall. If the shot hits a brick wall, the wall will disappear (i.e., in this turn). Well, given the description of a map, the positions of your tank and the target, how many turns will you take at least to arrive there?
Input
Output
Sample Input
3 4 YBEB EERE SSTE 0 0
Sample Output
8
思路:从Y到T的最小turn。turn:走一步路算一种,开炮也算一种。
B:土墙,可以被炮打坏,打坏以后就不在了。
R:河流,不能通过。
S:铁墙:不能通过,也不能被炮弹打坏。
E:空格,可以直接走过去。
因此,用优先队列,每次取出turn最小的那个,进行操作。知道走到T为止。因为土墙可以仙贝打坏,在通过,因此如果遇到土墙,可以认为进项了两个turn,
而遇到E空格是,只需走一步,进行一个turn。
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int cnv[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct Rac{
int x,y,cnt;
bool operator < (const Rac & p) const{
return cnt > p.cnt;
} //优先取cnt 最小的那个元素
};
char mp[305][305];
int visit[305][305];
int sx,sy,tx,ty;
int n,m;
int main()
{
while(scanf("%d %d",&m,&n),m!=0||n!=0)
{
getchar();
int i,j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%c",&mp[i][j]);
if(mp[i][j]=='Y')
{
sx=i;
sy=j;
}
else if(mp[i][j]=='T')
{
tx=i;
ty=j;
}
}
getchar();
} //找出终点,起点
/* for(i=0;i<m;i++)
{
puts(mp[i]);
}*/
memset(visit,0,sizeof(visit));
priority_queue<Rac>q;//优先队列
Rac s;
s.x=sx;
s.y=sy;
s.cnt=0;
visit[sx][sy]=1;
q.push(s);
bool ok=false;
while(!ok&&q.empty()==false) //到达T 或队列为空是,停止
{
Rac t=q.top();
q.pop();
for(i=0;i<4;i++) //上下左右操作
{
int x=t.x+cnv[i][0];
int y=t.y+cnv[i][1];
if(x>=0&&x<m&&y>=0&&y<n&&visit[x][y]==0&&mp[x][y]!='S'&&mp[x][y]!='R')//到达边界&&铁墙或河流不能通过
{
if(mp[x][y]=='E') //为空格时
{
visit[x][y]=1;
Rac t2;
t2.x=x;
t2.y=y;
t2.cnt=t.cnt+1;
q.push(t2);
}
else if(mp[x][y]=='B') //土墙时
{
visit[x][y]=1;
Rac t2;
t2.x=x;
t2.y=y;
t2.cnt=t.cnt+2;
q.push(t2);
}
else if(mp[x][y]=='T') //到达终点
{
ok=true;
printf("%d\n",t.cnt+1);
break;
}
}//if4
}
}
if(!ok) printf("-1\n"); //不能到达
}
return 0;
}