題意:
S是起點,T是終點,B是加氧氣點並花費一分鐘,. 是任何條件都可以走並花費一分鐘,#是要有氧氣的情況下可以走但是要花費兩分鐘,P是可以少一分鐘。
最多可以帶5個氧氣瓶,問從起點到終點最小花費時間。
題解:
每一點有6個狀態,即 0氧氣 到 5氧氣,跑BFS維護每個點的每個狀態只跑一次,用優先隊列來控制先走時間花費最少的狀態即可。
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <stack>
#include <cmath>
#include <deque>
#include <queue>
#include <list>
#include <set>
#include <map>
#define mem(a, b) memset(a, b, sizeof(a))
#define pi acos(-1)
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
int step[4][2] = {{1,0}, {0,1}, {-1,0}, {0,-1}};
struct node{
int x, y, o, t;
node(){};
node(int _x, int _y, int _o, int _t){
x = _x;
y = _y;
o = _o;
t = _t;
}
bool operator <(const node &a) const {
return t > a.t;
}
};
char mapp[105][105];
int mark[105][105][10];
int sx, sy, n, m;
priority_queue<node> q;
int bfs(){
mem(mark, 0);
while (!q.empty()) {
q.pop();
}
q.push(node(sx, sy, 0, 0));
while(!q.empty()){
node p = q.top();
q.pop();
if(mapp[p.x][p.y] == 'T'){
return p.t;
}
if(mark[p.x][p.y][p.o]){
continue;
}
mark[p.x][p.y][p.o] = 1;
for(int i = 0; i < 4; i++){
int nx = p.x+step[i][0], ny = p.y+step[i][1];
if(nx >= n || nx < 0 || ny >= m || ny < 0){
continue;
}
if(mapp[nx][ny] == '#' && p.o){
q.push(node(nx, ny, p.o-1, p.t+2));
}
else if(mapp[nx][ny] == 'B'){
q.push(node(nx, ny, p.o+1 > 5 ? 5 : p.o+1, p.t+1));
}
else if(mapp[nx][ny] == 'P'){
q.push(node(nx, ny, p.o, p.t));
}
else if(mapp[nx][ny] == '.' || mapp[nx][ny] == 'T' || mapp[nx][ny] == 'S'){
q.push(node(nx, ny, p.o, p.t+1));
}
}
}
return -1;
}
int main(){
while(scanf("%d %d", &n, &m), n, m){
for(int i = 0; i < n; i++){
scanf("%s", mapp[i]);
for(int j = 0; j < m; j++){
if(mapp[i][j] == 'S'){
sx = i;
sy = j;
}
}
}
int ans = bfs();
printf("%d\n", ans);
}
}