题意
题解
这本来是一道简单的bfs题,但自己平时代码习惯不好,导致比赛时T了还找不出原因(手动幽灵)。
主要原因是bfs返回位置不对。如果用优先队列做,从将终点进队到将终点出队会间隔很多个点。所以应该在将终点进队时就返回!谨记谨记!
代码
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn = 100+1;
const int INF = 0x3f3f3f3f;
const int dx[] = {0,0,-1,1};
const int dy[] = {-1,1,0,0};
struct pt{
int x,y;
int oxy;
int time;
pt(int x=0, int y=0, int o=0,int t=0):x(x),y(y),oxy(o),time(t){}
bool operator < (const pt &rsh)const{
return time>rsh.time;
}
};
char mp[maxn][maxn];
bool vis[maxn][maxn][6];
int n,m;
pt st,en;
int bfs(){
priority_queue<pt> qu;
qu.push(st);
while(!qu.empty()){
pt s = qu.top();qu.pop();
if(vis[s.x][s.y][s.oxy]) continue;
vis[s.x][s.y][s.oxy] = true;
for(int i = 0; i<4; i++){
int nx = s.x + dx[i];
int ny = s.y + dy[i];
if(nx<0||nx>=n||ny<0||ny>=m)continue;
if(mp[nx][ny]=='T'){
return s.time+1;
}
if(mp[nx][ny]=='P'){
qu.push(pt(nx, ny, s.oxy, s.time));
}
else if(mp[nx][ny]=='#'){
if(s.oxy>0)qu.push(pt(nx,ny,s.oxy-1,s.time+2));
}
else if(mp[nx][ny]=='B'){
if(s.oxy<5){
qu.push(pt(nx, ny, s.oxy+1, s.time+1));
}
else qu.push(pt(nx, ny, s.oxy, s.time+1));
}
else if(mp[nx][ny]=='.'||mp[nx][ny]=='S'){
qu.push(pt(nx, ny, s.oxy, s.time+1));
}
}
}
return -1;
}
int main(){
while(scanf("%d%d", &n, &m)!=EOF && n+m){
memset(vis, false, sizeof(vis));
for(int i = 0; i<n; i++){
scanf("%s", mp[i]);
for(int j = 0; j<m; j++){
if(mp[i][j]=='S'){
st.x = i;st.y = j;st.oxy = 0;
st.time = 0;
}
if(mp[i][j] == 'T'){
en.x = i;en.y = j;en.oxy = 0;
en.time = 0;
}
}
}
printf("%d\n", bfs());
}
}