HDU - 1043 反向BFS建表

Problem Description
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

題意:給你一個3*3的方格,方格里面的信息是以一行的信息給出的,比如樣例給的是2 3 4 1 5 x 7 6 8,對應的方格排列就是
2 3 4
1 3 x
7 6 8
那麼題目問,給定的狀態最終是否可以轉換爲1 2 3 4 5 6 7 8 x的形式;
(答案不唯一),如果不存在輸出unsolvable,存在一種方法的話,就輸出x這個模塊的移動方法,上下左右分別u、d、l、r;
分析:
首先,這個題目是多組輸入,那麼每次都去搜索的話必然會T掉,但是我們可以用打表的方法去實現,這樣的打表就9!種情況;
熟悉8數碼的小夥伴肯定知道很多處理方法,最笨的方法,我覺得是用STL裏面的map去做,當然時間上速度就會慢很多,但是不會T掉
在這裏插入圖片描述
下面是用STL的map實現的

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <set>
#include <utility>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define inf 0x3f3f3f3f
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
//priority_queue<int,vector<int> ,greater<int> >q;
const int N = 1e5 + 10;
const int mod = 1e9+7;
int fac[13];
int dy[]={-1,0,1,0},dx[]={0,1,0,-1};//移動方向
struct node{
    int pos;//x也可以說是9所在的位置;
    ll son;//可以理解爲後續的狀態編號
    int arr[11];
};
ll Cantor(int a[]){
    ll ans=0;
    for(int i=0;i<9;i++)
        ans=ans*10+a[i];
    return ans;
}
map<ll,ll>ma;
map<ll,char>maa;//記錄移動方向
void BFS(int a[]){
    node u,p;
    p.pos=8;
    for(int i=0;i<9;i++) p.arr[i]=a[i];
    ans[0].fa=0;
    p.son=Cantor(p.arr);
    ma[p.son]=-1;
    queue<node>q;
    q.push(p);

    int now_x,now_y,next_x,next_y;
    while(!q.empty()){
        u=q.front();
        q.pop();
        now_x=u.pos/3;
        now_y=u.pos%3;
        for(int i=0;i<4;i++){
            next_x=now_x+dx[i];
            next_y=now_y+dy[i];

            if(next_x<3 && next_x>=0 && next_y<3 && next_y>=0){
                p=u;
                p.pos=next_x*3+next_y;
                swap(p.arr[u.pos],p.arr[p.pos]);
                p.son=Cantor(p.arr);
                    ma[p.son]=u.son;
                    //這裏注意是反向的,這樣處理,在查詢輸出的時候方便
                    //因爲我們是從終態推初態的
                    if(i==0) maa[p.son]='r';
                    if(i==1) maa[p.son]='u';
                    if(i==2) maa[p.son]='l';
                    if(i==3) maa[p.son]='d';
                    q.push(p);
                }
            }
        }
    }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    int a[11];
    Jie();
    for(int i=1;i<=9;i++)
        a[i-1]=i;
    BFS(a);

    int in[11];
    char ch;
    while(scanf("%c",&ch)!=EOF){
        for(int i=0;ch!='\n';){
            if(ch=='x') in[i++]=9;
            else if(ch>='0' && ch<='8')
                in[i++]=ch-'0';
            scanf("%c",&ch);
        }
       ll p=Cantor(in);
        if(ma[p]==0)
            printf("unsolvable\n");
        else{
            while(p!=-1){
                cout<<maa[p];
                p=ma[p];
//                p=ans[p].fa;
            }
            printf("\n");
        }
    }
    return 0;
}

還有一種網上用的比較多的方法就是康拓展開,我是參考的下面這個博主的博客瞭解到了康拓展開
參考:https://www.cnblogs.com/Howe-Young/p/4348777.html

知道了原理了之後,相比STL的實現,就是存儲狀態的方法不一樣了,其他的方面都是相同的

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <set>
#include <utility>
#include <sstream>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define inf 0x3f3f3f3f
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
//priority_queue<int,vector<int> ,greater<int> >q;
const int N = 1e5 + 10;
const int mod = 1e9+7;
int fac[13];
int dy[]={-1,0,1,0},dx[]={0,1,0,-1};//移動方向
struct node{
    int pos;//x也可以說是9所在的位置;
    int son;//可以理解爲後續的狀態編號
    int arr[11];
};
void Jie(){//計算階乘
    fac[0]=fac[1]=1;
    for(int i=2;i<10;i++)
        fac[i]=fac[i-1]*i;
}
int Cantor(int a[]){//康託展開
    int ans=0,cnt=0;
    for(int i=0;i<9;i++){
        cnt=0;
        for(int j=i+1;j<9;j++){
            if(a[j]<a[i]) cnt++;
        }
        ans+=cnt*fac[8-i];
    }
    return ans;
}
struct node1{
    int fa;//前驅編號
    char step;
}ans[370000];//近似9!種全排結果
void BFS(int a[]){
    node u,p;
    p.pos=8,p.son=0;
    for(int i=0;i<9;i++) p.arr[i]=a[i];
    ans[0].fa=0;
    queue<node>q;
    q.push(p);

    int now_x,now_y,next_x,next_y;
    while(!q.empty()){
        u=q.front();
        q.pop();
        now_x=u.pos/3;
        now_y=u.pos%3;
        for(int i=0;i<4;i++){
            next_x=now_x+dx[i];
            next_y=now_y+dy[i];

            if(next_x<3 && next_x>=0 && next_y<3 && next_y>=0){
                p=u;
                p.pos=next_x*3+next_y;
                swap(p.arr[u.pos],p.arr[p.pos]);
                p.son=Cantor(p.arr);
                if(ans[p.son].fa==-1){
                    ans[p.son].fa=u.son;
                    if(i==0) ans[p.son].step='r';
                    if(i==1) ans[p.son].step='u';
                    if(i==2) ans[p.son].step='l';
                    if(i==3) ans[p.son].step='d';
                    q.push(p);
                }
            }
        }
    }
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    #endif // ONLINE_JUDGE
    int a[11];
    Jie();
    for(int i=1;i<=9;i++)
        a[i-1]=i;
    for(int i=0;i<370000-10;i++) ans[i].fa=-1;
    BFS(a);

    int in[11];
    char ch;
    while(scanf("%c",&ch)!=EOF){
        for(int i=0;ch!='\n';){
            if(ch=='x') in[i++]=9;
            else if(ch>='0' && ch<='8')
                in[i++]=ch-'0';
            scanf("%c",&ch);
        }
        int p=Cantor(in);

        if(ans[p].fa==-1)
            printf("unsolvable\n");
        else{
            while(p!=0){
                printf("%c",ans[p].step);
                p=ans[p].fa;
            }
            printf("\n");
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章