HDU1043BFS 康托展开 八数码

经典的八数码问题

至于康托展开,百度知道。。。

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

using namespace std;

int jc[11] = {1,1,2,6,24,120,720,5040,40320,362880};
bool vis[444444];
string path[444444];
int aim;
int mx[4] = {0,0,1,-1};
int my[4] = {1,-1,0,0};
char direction[4] = {'l','r','u','d'};
struct State{
    int x,y;
    int s[11];
    int state;
    string path;
};

char mp[4][4];

bool in(State a){
    if(a.x >= 0 && a.x < 3 && a.y >= 0 && a.y < 3)
        return true;
    else
        return false;
}

int contor(int s[]){
    int sum = 0;
    for(int i = 0 ; i < 9 ; i ++){
        int num = 0;
        for(int j = i + 1 ; j < 9 ; j ++){
            if(s[j] < s[i]){
                num++;
            }
        }
        sum += num*jc[9-i-1];
    }
    return sum + 1;
}

queue<State> q;
void BFS(){
    memset(vis,0,sizeof(vis));
    State s;
    for(int i = 0 ; i < 8 ; i ++){
        s.s[i] = i+1;
    }
    s.s[8] = 0;
    s.state = contor(s.s);
    s.x = 2;
    s.y = 2;
    s.path = "";
    path[s.state] = "";
    vis[s.state] = 1;
    q.push(s);
    while(!q.empty()){
        State cnt = q.front();
        q.pop();
        for(int i = 0 ; i < 4 ; i ++){
            State nt = cnt;
            nt.x = cnt.x + mx[i];
            nt.y = cnt.y + my[i];
            if(in(nt) == 0)
                continue;
            nt.s[cnt.x*3+cnt.y] = nt.s[nt.x*3+nt.y];
            nt.s[nt.x*3+nt.y] = 0;
            nt.state = contor(nt.s);
            if(vis[nt.state] == 0){
                path[nt.state] = direction[i]+nt.path;
                nt.path = path[nt.state];
                vis[nt.state] = 1;
                q.push(nt);
            }
        }
    }
}

int main()
{
    char str;
    State now;
    BFS();
    while(cin>>str){
        if(str == 'x'){
            now.x = 0;
            now.y = 0;
            now.s[0] = 0;
        }
        else
            now.s[0] = str - '0';
        for(int i = 1 ; i < 9 ; i ++){
            cin>>str;
            if(str == 'x'){
                now.x = i/3;
                now.y = i%3;
                now.s[i] = 0;
            }
            else
                now.s[i] = str-'0';
        }
        now.state = contor(now.s);
        if(vis[now.state] == 1)
            cout<<path[now.state]<<endl;
        else
            cout<<"unsolvable"<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值