HDU - 5012 Dice(bfs+hash)

题意:

给定两个骰子,要按照只能左右前后的翻转方式,将两个骰子摆成状态一直的顺序,问最少需要多少步?

解析:

直接宽度优先搜索的四个方向换成四种状态。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
bool vis[700000];
struct Dice {
    int v[6];
    int dist;
    Dice(int _v[],int _dist) {
        memcpy(v, _v, sizeof(v));
        dist = _dist;
    }
    Dice() {
        memset(v, 0, sizeof(v));
        dist = 0;
    }
    int hash() {
        int sum = 0;
        for(int i = 0; i < 6; i++)
            sum = sum * 10 + v[i];
        return sum;
    }
}A, B;
Dice rotate(Dice front,int dir) {
    Dice dice = front;
    int tmp;
    if(dir == 0) {
        tmp = dice.v[2];
        dice.v[2] = dice.v[0];
        dice.v[0] = dice.v[3];
        dice.v[3] = dice.v[1];
        dice.v[1] = tmp;
        return dice;
    }else if(dir == 1) {
        tmp = dice.v[3];
        dice.v[3] = dice.v[0];
        dice.v[0] = dice.v[2];
        dice.v[2] = dice.v[1];
        dice.v[1] = tmp;
        return dice;
    }else if(dir == 2) {
        tmp = dice.v[4];
        dice.v[4] = dice.v[0];
        dice.v[0] = dice.v[5];
        dice.v[5] = dice.v[1];
        dice.v[1] = tmp;
        return dice;
    }else if(dir == 3) {
        tmp = dice.v[5];
        dice.v[5] = dice.v[0];
        dice.v[0] = dice.v[4];
        dice.v[4] = dice.v[1];
        dice.v[1] = tmp;
        return dice;
    }
    return dice;
}
int bfs() {
    memset(vis, false, sizeof(vis));
    queue<Dice> que;
    que.push(A);
    vis[A.hash()] = true;
    Dice front, rear;
    while(!que.empty()) {
        front = que.front();
        que.pop();
        if(!memcmp(front.v, B.v, sizeof(B.v)))
            return front.dist;
        for(int i = 0; i < 4; i++) {
            rear = rotate(front, i);
            if(!vis[rear.hash()]) {
                vis[rear.hash()] = true;
                rear.dist = front.dist + 1;
                que.push(rear);
            }
        }
    }
    return -1;
}
int main() {
    while(scanf("%d", &A.v[0]) != EOF) {
        for(int i = 1; i < 6; i++) {
            scanf("%d", &A.v[i]);
        }
        for(int i = 0; i < 6; i++) {
            scanf("%d", &B.v[i]);
        }
        printf("%d\n", bfs());
    }
    return 0;
}

你可能感兴趣的:(HDU,5012)