坦克大战的最短路问题。E代表空地,B代表砖墙,一发炮弹可以解决,S代表铁墙,无法炸毁,R代表河流,无法通过,Y代表当前位置,T代表目标位置。每回合可以走一步,或者来一发,求最终到达目标位置的最少回合数。无法到达输出-1。
最短路嘛,spfa直接解决。bfs+优先队列也是可以做的,不过优先队列怎么用啊。。。各种头文件求指导。。。
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
typedef struct coordinate {
int x,y;
int turn;
}point;
const int inf = 1<<20;
const int MAX = 305;
int n,m;
int map[MAX][MAX];
int dis[MAX][MAX];
bool had[MAX][MAX];
queue <point> q;
void bfs(int sx,int sy){
memset(had,0,sizeof(had));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
dis[i][j]=inf;
}
}
dis[sx][sy]=0;
point temp;
temp.x=sx; temp.y=sy;
q.push(temp);
had[sx][sy]=1;
while(!q.empty()){
point t=q.front(); q.pop();
had[t.x][t.y]=0;
if(t.x-1>=0 && dis[t.x-1][t.y]>dis[t.x][t.y]+map[t.x-1][t.y]) {
dis[t.x-1][t.y]=dis[t.x][t.y]+map[t.x-1][t.y];
if(!had[t.x-1][t.y]){
had[t.x-1][t.y]=1;
point tt=t;
tt.x--;
q.push(tt);
}
}
if(t.x+1<n && dis[t.x+1][t.y]>dis[t.x][t.y]+map[t.x+1][t.y]) {
dis[t.x+1][t.y]=dis[t.x][t.y]+map[t.x+1][t.y];
if(!had[t.x+1][t.y]){
had[t.x+1][t.y]=1;
point tt=t;
tt.x++;
q.push(tt);
}
}
if(t.y-1>=0 && dis[t.x][t.y-1]>dis[t.x][t.y]+map[t.x][t.y-1]) {
dis[t.x][t.y-1]=dis[t.x][t.y]+map[t.x][t.y-1];
if(!had[t.x][t.y-1]){
had[t.x][t.y-1]=1;
point tt=t;
tt.y--;
q.push(tt);
}
}
if(t.y+1<m && dis[t.x][t.y+1]>dis[t.x][t.y]+map[t.x][t.y+1]) {
dis[t.x][t.y+1]=dis[t.x][t.y]+map[t.x][t.y+1];
if(!had[t.x][t.y+1]){
had[t.x][t.y+1]=1;
point tt=t;
tt.y++;
q.push(tt);
}
}
}
}
int main(){
//freopen("in.txt","r",stdin);
while(cin >> n >> m){
if(!n && !m) break;
int sx=-1,sy=-1;
int tx=-1,ty=-1;
for(int i=0;i<n;i++){
char ss[305];
scanf("%s",ss);
for(int j=0;j<m;j++){
if(ss[j]=='Y') {
sx=i; sy=j;
map[i][j]=1;
}
else if(ss[j]=='T') {
tx=i; ty=j;
map[i][j]=1;
}
else if(ss[j]=='S' || ss[j]=='R') {
map[i][j]=inf;
}
else if(ss[j]=='B') {
map[i][j]=2;
}
else if(ss[j]=='E') {
map[i][j]=1;
}
}
}
bfs(sx,sy);
if(tx==-1) cout<<-1<<endl;
else if(dis[tx][ty]!=inf) cout<<dis[tx][ty]<<endl;
else cout<<-1<<endl;
}
return 0;
}