POJ 3322 BFS

题意

传送门 POJ 3322 Bloxorz I

题解

长方体当前的状态为其横、纵坐标与摆放状态组成的三元组,为了方便表示,只取长方体左上方的位置作为横、纵坐标状态, B F S BFS BFS 求解即可。

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define maxn 505
struct node
{
    int x, y, s;
} s, t;
const int dx[3][4] = {{0, 0, -2, 1}, {0, 0, -1, 2}, {0, 0, -1, 1}};
const int dy[3][4] = {{1, -2, 0, 0}, {1, -1, 0, 0}, {2, -1, 0, 0}};
const int ds[3][4] = {{2, 2, 1, 1}, {1, 1, 0, 0}, {0, 0, 2, 2}};
const int _dx[4] = {0, 0, -1, 1}, _dy[4] = {-1, 1, 0, 0};
char mp[maxn][maxn];
int R, C, dis[maxn][maxn][3];

bool judge(int x, int y)
{
    return 0 <= x && x < R && 0 <= y && y < C;
}

bool judge(node &t)
{
    if (!judge(t.x, t.y) || mp[t.x][t.y] == '#')
        return 0;
    if (t.s == 0 && mp[t.x][t.y] == 'E')
        return 0;
    if (t.s == 1 && mp[t.x + 1][t.y] == '#')
        return 0;
    if (t.s == 2 && mp[t.x][t.y + 1] == '#')
        return 0;
    return 1;
}

void bfs()
{
    memset(dis, -1, sizeof(dis));
    dis[s.x][s.y][s.s] = 0;
    queue<node> q;
    q.push(s);
    while (!q.empty())
    {
        node v = q.front();
        q.pop();
        if (v.x == t.x && v.y == t.y && v.s == t.s)
        {
            printf("%d\n", dis[t.x][t.y][t.s]);
            return;
        }
        node nxt;
        for (int i = 0; i < 4; ++i)
        {
            nxt.x = v.x + dx[v.s][i], nxt.y = v.y + dy[v.s][i], nxt.s = ds[v.s][i];
            if (judge(nxt) && dis[nxt.x][nxt.y][nxt.s] == -1)
                dis[nxt.x][nxt.y][nxt.s] = dis[v.x][v.y][v.s] + 1, q.push(nxt);
        }
    }
    puts("Impossible");
}

int main()
{
    while (~scanf("%d%d", &R, &C) && (R | C))
    {
        for (int i = 0; i < R; ++i)
            scanf(" %s", mp[i]);
        bool fs = 1, ft = 1;
        for (int i = 0; i < R; ++i)
        {
            for (int j = 0; (fs || ft) && j < C; ++j)
            {
                if (mp[i][j] == 'O')
                    t.x = i, t.y = j, t.s = 0, mp[i][j] = '.', ft = 0;
                else if (mp[i][j] == 'X')
                {
                    s.x = i, s.y = j, s.s = 0, mp[i][j] = '.', fs = 0;
                    for (int k = 0; k < 4; ++k)
                    {
                        int nx = i + _dx[k], ny = j + _dy[k];
                        if (judge(nx, ny) && mp[nx][ny] == 'X')
                            s.x = min(s.x, nx), s.y = min(s.y, ny), s.s = (k < 2 ? 2 : 1), mp[nx][ny] = '.';
                    }
                }
            }
        }
        bfs();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值