hdu1180 (bfs + 优先队列)

题目链接: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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值