Many of us had played the game "Battle city" in our childhood, and some people (like me) even often play it on computer now.
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
The input consists of several test cases. The first line of each test case contains two integers M and N (2 <= M, N <= 300). Each of the following M lines contains N uppercase letters, each of which is one of 'Y' (you), 'T' (target), 'S' (steel wall), 'B' (brick wall), 'R' (river) and 'E' (empty space). Both 'Y' and 'T' appear only once. A test case of M = N = 0 indicates the end of input, and should not be processed.
Output
For each test case, please output the turns you take at least in a separate line. If you can't arrive at the target, output "-1" instead.
Sample Input
3 4 YBEB EERE SSTE 0 0
Sample Output
8
bfs细心细心细心重要的事情说三遍
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n,m;
int ans;
char ma[500][500];
bool vis[500][500];
struct node{
int x,y;
int sum;
friend bool operator < (node a,node b){
return a.sum>b.sum;
}
};
int D[4][2]={1,0,-1,0,0,1,0,-1};
void bfs(int a,int b,int c,int d)
{
priority_queue<node>que;//每次定义的时候 效果等同于清空 ,若定义成全局,每次需要清空
ans=-1;
memset(vis,0,sizeof(vis));
node e1,e2,e3;
e1.x=a;
e1.y=b;
e1.sum=0;
vis[a][b]=1;
que.push(e1);
while(!que.empty()){
e2=que.top();
que.pop();
if(e2.x==c && e2.y==d){
ans=e2.sum;
break;
}
for(int i=0;i<4;i++){
e3.x=e2.x+D[i][0];
e3.y=e2.y+D[i][1];//不要数组名与变量名相同
if(e3.x<0 || e3.y<0 || e3.x>=n || e3.y>=m) continue;
if(vis[e3.x][e3.y]) continue;
if(ma[e3.x][e3.y]=='S' || ma[e3.x][e3.y]=='R') continue;
if(ma[e3.x][e3.y]=='B')
e3.sum=e2.sum+2;
else if(ma[e3.x][e3.y]=='E' ||ma[e3.x][e3.y]=='T')
e3.sum=e2.sum+1;
que.push(e3);
vis[e3.x][e3.y]=1;
}
}
}
int main()
{
int a,b,c,d;
while(cin>>n>>m,n||m){
for(int i=0;i<n;i++)
cin>>ma[i];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(ma[i][j]=='Y'){
a=i;b=j;
}
if(ma[i][j]=='T'){
c=i;d=j;
}
}
}
bfs(a,b,c,d);
if(ans==-1) cout<<"-1"<<endl;
else cout<<ans<<endl;
}
return 0;
}