坦克大戰的最短路問題。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;
}