题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1180
分析
这道题可以采用bfs+优先队列。
注意:
1.优先队列将花费时间短的排在前面
2.过桥的时候注意判断桥的方向与当前的前进方向是否相同,不同的时候要停下等待1分钟
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int n,m;
char a[25][25];
int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}};
struct Node {
int x,y,time;
bool operator < (const Node& b) const {
return time > b.time;//时间短的排在前
}
};
bool isValid(int x,int y)
{
return (x >= 0) && (x < n) && (y >= 0) && (y < m) && (a[x][y] != '*');
}
void check(int& x,int& y,int& time,int i)//判断是不是桥以及桥的方向和前进方向
{
if(a[x][y] == '|') {//桥的初始状态
if(time % 2 == 0) {//桥当前的状态
if(i == 2 || i == 3) time++;//与前进方向不一致就等待1分钟
} else {
if(i == 0 || i == 1) time++;
}
x += dir[i][0];//通向桥的对岸的点
y += dir[i][1];
}
if(a[x][y] == '-') {
if(time % 2 == 0) {
if(i == 0 || i == 1) time++;
} else {
if(i == 2 || i == 3) time++;
}
x += dir[i][0];
y += dir[i][1];
}
time++;
}
void bfs(int x,int y)
{
priority_queue<Node> q;
Node start = {x,y,0};
q.push(start);
a[x][y] = '*';
while(!q.empty()) {
Node head = q.top();
q.pop();
for(int i = 0; i < 4; i++) {
int nx = head.x + dir[i][0];
int ny = head.y + dir[i][1];
if(isValid(nx,ny)) {
int time = head.time;
check(nx,ny,time,i);
if(isValid(nx,ny)) {
if(a[nx][ny] == 'T') {
printf("%d\n",time);
return;
}
Node node = {nx,ny,time};
q.push(node);
a[nx][ny] = '*';
}
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m)) {
int x,y;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) {
scanf(" %c",&a[i][j]);
if(a[i][j] == 'S') x = i,y = j;
}
bfs(x,y);
}
return 0;
}