//
// 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;
}
POJ 1077 Eight(bfs八数码问题)
最新推荐文章于 2020-07-28 10:21:55 发布