bfs+优先队列
代码
//bfs
//#include<bits/stdc++.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define CL(a,b) memset(a,b,sizeof(a))
const int maxm=305;
const int maxn=305;
char mp[maxm][maxn];
int vis[maxm][maxn];//记录是否处理过
struct node{
int x,y;
int step;
node(int x_,int y_,int s_):x(x_),y(y_),step(s_){}
};
bool operator < (node a,node b){
return a.step>b.step;
}
int mv[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
//优先队列
int m,n;
int bfs(node begin,int endx,int endy){
priority_queue<node> que;
vis[begin.x][begin.y]=1;
que.push(begin);
while(!que.empty()){
node tmp=que.top();
que.pop();
//printf("db %d %d step %d
",tmp.x,tmp.y,tmp.step);
if(tmp.x==endx&&tmp.y==endy) return tmp.step;
int tmpx,tmpy,tmps;
for(int i=0;i<4;i++){
tmpx=tmp.x+mv[i][0];
tmpy=tmp.y+mv[i][1];
if(tmpx<0||tmpx>=m||tmpy<0||tmpy>=n||vis[tmpx][tmpy]||mp[tmpx][tmpy]=='S'||mp[tmpx][tmpy]=='R') continue;//依旧可能出现相同坐标都在队列中
else if(mp[tmpx][tmpy]=='B') tmps=tmp.step+2;
else tmps=tmp.step+1;
node t=node(tmpx,tmpy,tmps);
vis[tmpx][tmpy]=1;
que.push(t);
//else if(mp[tmpx][tmpy]=='B'){node t=node(tmpx,tmpy,tmp.step+2);vis[tmpx][tmpy]=1;que.push(t);}
//else if(mp[tmpx][tmpy]=='E'||mp[tmpx][tmpy]=='T'){node t=node(tmpx,tmpy,tmp.step+1);vis[tmpx][tmpy]=1;que.push(t);}
}
}
return -1;//no find
}
node beg=node(0,0,0);
int endx,endy;
int main(){
while(scanf("%d %d",&m,&n)&&m!=0){
//CL(mp,0);
CL(vis,0);
/*
while(!que.empty()){
que.pop();
}
*/
for(int i=0;i<m;i++){
scanf("%s",mp[i]);
for(int j=0;j<n;j++){
if(mp[i][j]=='Y'){
beg.x=i,beg.y=j,beg.step=0;
}
if(mp[i][j]=='T'){
endx=i,endy=j;
}
}
}
int ans=bfs(beg,endx,endy);
printf("%d
",ans);
}
return 0;
}
发现
对运算符的重载放在结构体外面更快,16ms-->0ms