HDU - 1043 Eight 八数码 境界二 (BFS+康托展开)

The 15-puzzle has been around for over 100 years; even if you don’t know it by that name, you’ve seen it. It is constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. Let’s call the missing tile ‘x’; the object of the puzzle is to arrange the tiles so that they are ordered as:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 x

where the only legal operation is to exchange ‘x’ with one of the tiles with which it shares an edge. As an example, the following sequence of moves solves a slightly scrambled puzzle:

1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8
9 x 10 12 9 10 x 12 9 10 11 12 9 10 11 12
13 14 11 15 13 14 11 15 13 14 x 15 13 14 15 x
r-> d-> r->

The letters in the previous row indicate which neighbor of the ‘x’ tile is swapped with the ‘x’ tile at each step; legal values are ‘r’,’l’,’u’ and ‘d’, for right, left, up, and down, respectively.

Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable version of the puzzle, and
frustrating many people. In fact, all you have to do to make a regular puzzle into an unsolvable one is to swap two tiles (not counting the missing ‘x’ tile, of course).

In this problem, you will write a program for solving the less well-known 8-puzzle, composed of tiles on a three by three
arrangement.
Input
You will receive, several descriptions of configuration of the 8 puzzle. One description is just a list of the tiles in their initial positions, with the rows listed from top to bottom, and the tiles listed from left to right within a row, where the tiles are represented by numbers 1 to 8, plus ‘x’. For example, this puzzle

1 2 3
x 4 6
7 5 8

is described by this list:

1 2 3 x 4 6 7 5 8
Output
You will print to standard output either the word “unsolvable”, if the puzzle has no solution, or a string consisting entirely of the letters ‘r’, ‘l’, ‘u’ and ‘d’ that describes a series of moves that produce a solution. The string should include no spaces and start at the beginning of the line. Do not print a blank line between cases.
Sample Input
2 3 4 1 5 x 7 6 8
Sample Output
ullddrurdllurdruldr

经典到我都不用描述大家应该都知道是什么的题目,因为是多组样例,所以我们要反向搜索,即从开始阶段拓展到不能拓展位置,然后记录其中的操作,最后再把所有的结果存起来,输入对应的结果就输出对应的操作就行了,说起来是很简单,的但是其中操作确实并不容易啊,因为特别容易超内存,所以我们要把每个序列都哈希成一个固定的值,所以用到了Cantor展开,然后因为我们不能每个结果都存储到这一步的操作序列(也是超内存)所以我们要记录每个节点的父亲节点和父亲节点到该节点的操作(只有一个)最后我们向上遍历就行了。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int MAX = 362880;
pair<int,char> p[MAX];//first记录父亲节点,second记录从父亲节点到当前节点的变化。
bool book[MAX];//判断这个节点是否出现过
int Fac[11];//记录阶乘
void init(){
    Fac[0] = 1;
    for(int i=1;i<=10;++i){
        Fac[i] = Fac[i-1]*i;
    }
    memset(book,0,sizeof(book));
}
//哈希成一个固定的值
int Cantor(string str){
    int res = 0,len = (int)str.length();
    for(int i=0;i<len;++i){
        int Count = 0;
        for(int j=i+1;j<len;++j){
            if(str[j] < str[i])
                Count++;
        }
        res += Count*Fac[len-i-1];
    }
    return res;
}

const int xx[] = {0,1,0,-1};
const int yy[] = {1,0,-1,0};
const char ch[] = {'l','u','r','d'};

class Node{
public:
    char x[4][4];
    int px,py;
    Node();
    void change(int tx,int ty){
        swap(x[tx][ty],x[px][py]);
        px = tx,py = ty;
    }
};
//把数码棋盘转为字符串
string tostring(char x[][4]){
    string res = "";
    for(int i=1;i<=3;++i){
        for(int j=1;j<=3;++j){
            res += x[i][j];
        }
    }
    return res;
}
//求出其位置
int tovalue(Node v){
    return Cantor(tostring(v.x));
}
void BFS(Node Begin){
    queue<Node> que;
    int value = tovalue(Begin);
    if(!book[value]){
        book[value] = true;
        p[0].first = 0;
        que.push(Begin);
    }
    while(!que.empty()){
        Node v = que.front();que.pop();
        for(int i=0;i<4;++i){
            int tx = v.px + xx[i];
            int ty = v.py + yy[i];
            if(tx < 1 || tx > 3 || ty <1 || ty > 3)
                continue;
            Node nex = v;
            nex.change(tx,ty);
            value = tovalue(nex);
            if(!book[value]){
                book[value] = true;
                p[value].first = tovalue(v);
                p[value].second = ch[i];
                que.push(nex);
            }
        }
    }
}

int main(void){
    init();
    Node Begin;
    for(int i=1;i<=3;++i){
        for(int j=1;j<=3;++j){
            Begin.x[i][j] = (char)((i-1)*3+j + '0');
        }
    }
    Begin.px = Begin.py = 3;
    BFS(Begin);
    string str;
    while(getline(cin,str)){
        Node v;
        int Px = 1,Py = 1;
        for(int i=0;i<str.length();++i){
            if(str[i] != ' '){
            if(Py == 4){
                Py = 1;
                Px++;
            }
            if(str[i] == 'x'){
                v.x[Px][Py] = '9';
                v.px = Px;
                v.py = Py;
            }
            else
                v.x[Px][Py] = str[i];
                Py++;
            }
        }
        if(!book[tovalue(v)]){
            cout << "unsolvable" << endl;
        }
        else{
            string res = "";
            int k = tovalue(v);//从这个节点向上搜索。
            while(k != 0){
                res += p[k].second;
                k = p[k].first;
            }
            cout << res << endl;
        }
    }
    return 0;
}
Node::Node(){
    px = py = 0;
    memset(x,0,sizeof(x));
}

猜你喜欢

转载自blog.csdn.net/zhao5502169/article/details/81099406