hdu 5012 Dice(隐式图搜索)

582 篇文章 0 订阅
9 篇文章 0 订阅

题目链接:hdu 5012 Dice

题目大意:给出一个立方体6个面的值,问说最少经过次旋转得到目标状态。

解题思路:隐式图搜索,直接将一个状态映射成一个整数,然后对应BFS。

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;
typedef int Mat[10];

const int maxn = 100005;
const int INF = 0x3f3f3f3f;
const int dir[4][6] = { {3, 2, 0, 1, 4, 5}, 
                        {2, 3, 1, 0, 4, 5},
                        {5, 4, 2, 3, 0, 1},
                        {4, 5, 2, 3, 1, 0}};

Mat S, E;
int d[maxn];

bool init () {
    for (int i = 0; i < 6; i++)
        if (scanf("%d", &S[i]) != 1)
            return false;
    for (int i  = 0; i < 6; i++)
        if (scanf("%d", &E[i]) != 1)
            return false;

    for (int i = 0; i < 6; i++) {
        S[i]--;
        E[i]--;
    }
    return true;
}

int get_hash(Mat x) {
    int ret = 0;
    for (int i = 0; i < 6; i++)
        ret = ret * 6 + x[i];
    return ret;
}

void reback(int u, Mat a) {
    for (int i = 5; i >= 0; i--) {
        a[i] = u % 6;
        u /= 6;
    }
}

int rotate (int u, int x) {
    Mat a, b;
    reback(u, a);
    for (int i = 0; i < 6; i++)
        b[i] = a[dir[x][i]];
    return get_hash(b);
}

int bfs (int s, int e) {
    memset(d, INF, sizeof(d));

    queue<int> que;
    que.push(s);
    d[s] = 0;

    if (s == e)
        return 0;

    while (!que.empty()) {
        int u = que.front();
        que.pop();

        for (int i = 0; i < 4; i++) {
            int v = rotate(u, i);

            if (d[v] > d[u] + 1) {
                d[v] = d[u] + 1;
                que.push(v);
            }

            if (v == e)
                return d[v];
        }
    }
    return -1;
}

int main () {
    while (init()) {
        printf("%d\n", bfs(get_hash(S), get_hash(E)));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值