POJ 1077 Eight(bfs八数码问题)

//
//  main.cpp
//  Richard
//
//  Created by 邵金杰 on 16/8/30.
//  Copyright © 2016年 邵金杰. All rights reserved.
//



#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=400000;
int ha[9]={1,1,2,6,24,120,720,5040,40320};
int End[9]={1,2,3,4,5,6,7,8,0};
struct node{
    int sta[9];
    int pos;
    int hash;
    string out;
};
int vis[maxn];
int contor(int a[9])
{
    int res=0,k;
    for(int i=0;i<9;i++)
    {
        k=0;
        for(int j=i+1;j<9;j++)
        {
            if(a[i]>a[j]) k++;
        }
        res+=k*ha[9-1-i];
    }
    return res;
}
bool reverse(int a[9])
{
    int times=0;
    for(int i=0;i<9;i++)
    {
        if(a[i]==0) continue;
        for(int j=i+1;j<9;j++)
        {
            if(a[j]==0) continue;
            if(a[i]>a[j]) times++;
        }
    }
    return times&1;
}
void swap(int *a,int x,int y)
{
    int temp=a[x];
    a[x]=a[y];
    a[y]=temp;
}
bool inside(int x,int y)
{
    return x<0||x>2||y<0||y>2;
}
int dx[4]={-1,0,1,0};
int dy[4]={0,-1,0,1};
char dir[5]="uldr";
void solve(int a[9])
{
    memset(vis,0,sizeof(vis));
    int endhash=contor(End);
    int nowhash=contor(a);
    if(endhash==nowhash){
        printf("\n");
        return ;
    }
    vis[nowhash]=1;
    node state;
    state.hash=nowhash;
    memcpy(state.sta,a,sizeof(int)*(9));
    for(int i=0;i<9;i++) if(state.sta[i]==0) {state.pos=i;break;}
    state.out="";
    queue<node> q;
    q.push(state);
    node now,next;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        if(now.hash==endhash) {cout<<now.out<<endl;return ;}
        int x=now.pos/3,y=now.pos%3;
        for(int i=0;i<4;i++)
        {
            next=now;
            int nx=x+dx[i];
            int ny=y+dy[i];
            if(inside(nx,ny)) continue;
            next.pos=nx*3+ny;
            swap(next.sta,now.pos,next.pos);
            next.hash=contor(next.sta);
            if(vis[next.hash]) continue;
            vis[next.hash]=1;
            next.out+=dir[i];
            q.push(next);
        }
    }
    printf("unsolvable\n");
}
int main()
{
    char buf[100];
    while(gets(buf))
    {
        int a[9],k=0;
        int len=(int)strlen(buf);
        for(int i=0;i<len;i++)
        {
            if(buf[i]=='x') {a[k]=0;k++;}
            if(buf[i]>='1'&&buf[i]<='9') {a[k]=buf[i]-'0';k++;}
        }
        if(reverse(a))
        {
            printf("unsolvable\n");
            continue;
        }
        solve(a);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值