题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1180
需要用到广搜和优先队列,而本题中的优先队列,就是要使得当前步数小的先出队列
当前坐标结构体的定义
struct node{
int x,y,step;
bool operator <(const node &a)const {
return step>a.step;//步数小的先出队列
}
}init;
特殊情况:当遇到楼梯方向与前进方向不一致时,可以等待1分钟,再前进。
贴上代码
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int n, m, sx, sy, ex, ey;
int status[22][22];
char maze[22][22];
int dir[4][2] = {0, -1, 0, 1, 1, 0, -1, 0};
struct node{
int x,y,step;
bool operator <(const node &a)const {
return step>a.step;//步数小的先出队列
}
}init;
bool judge(node no)
{
if(no.x<1||no.x>n||no.y<1||no.y>m||maze[no.x][no.y]=='*'||(status[no.x][no.y]&&no.step>=status[no.x][no.y]))
return false;
return true;
}
int bfs()
{
init.x = sx;init.y = sy;
init.step = 0;
status[init.x][init.y] = 1;
priority_queue<node> p;
while (!p.empty())
p.pop();
p.push(init);
while (!p.empty())
{
node past = p.top();
p.pop();
node now;
for (int i = 0; i < 4; i++) {
now.x = past.x + dir[i][0];
now.y = past.y + dir[i][1];
now.step = past.step + 1;
if (!judge(now)) continue;
if (maze[now.x][now.y] == '|') {
if (now.x == past.x && (past.step & 1) == 0)
now.step++;
if (now.y == past.y && (past.step & 1) == 1)
now.step++;
now.x += dir[i][0];
now.y += dir[i][1];
}
if (maze[now.x][now.y] == '-') {
if (now.x == past.x && (past.step & 1) == 1)
now.step++;
if (now.y == past.y && (past.step & 1) == 0)
now.step++;
now.x += dir[i][0];
now.y += dir[i][1];
}
if (!judge(now)) continue;
if (now.x == ex && now.y == ey)
return now.step;
status[now.x][now.y] = now.step;
p.push(now);
}
}
return 0;
}
int main()
{
while (cin >> n >> m)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> maze[i][j];
if (maze[i][j] == 'S') {
sx = i;sy = j;
}
if (maze[i][j] == 'T') {
ex = i; ey = j;
}
}
}
memset(status,0,sizeof(status));
int ans = bfs();
cout << ans << endl;
}
return 0;
}