题目:http://acm.hdu.edu.cn/showproblem.php?pid=1043
经典搜索题。。。我用map+BFS胡搞出来的。因为测试数据比较多,所以从预处理了下。从结果开始暴搜。所以搜索方向反向。
#include <iostream>
#include<string>
#include<queue>
#include<map>
using namespace std;
struct node
{
string str;
string path ;
int place;
node(){
place=0;
}
};
int beginIndex;
string begin;
string end = "123456780";
int move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
char c_dir[] = {'d', 'u', 'r', 'l'};
map<string ,node > mm;
void bfs()
{
queue<node > q;
node temp;
temp.place = beginIndex; temp.str=begin;
temp.path="";
mm[begin].place=1;
q.push(temp);
while(!q.empty()){
node cur = q.front(),next; q.pop();
for(int i=0;i<4;i++){
next=cur;
int x=cur.place/3+move[i][0];
int y=cur.place%3+move[i][1];
if(x<0||x>2||y<0||y>2) continue;
string tstr = cur.str ;
if(i==0){
tstr[cur.place-3]=cur.str[cur.place];
tstr[cur.place]= cur.str[cur.place-3];
next.place-=3;
// cout<<1<<endl;
}
else if(i==1){
tstr[cur.place+3]=cur.str[cur.place];
tstr[cur.place]= cur.str[cur.place+3];
next.place+=3;
}
else if(i==2){
tstr[cur.place-1]=cur.str[cur.place];
tstr[cur.place]= cur.str[cur.place-1];
next.place-=1;
}
else{
tstr[cur.place+1]=cur.str[cur.place];
tstr[cur.place]= cur.str[cur.place+1];
next.place+=1;
}
next.str=tstr;
next.path+=c_dir[i];
if(mm[next.str].place==0){
mm[next.str].path=next.path;
mm[next.str].place=1;
q.push(next);
// cout<<next.str<<endl;
}
}
}
// return false;
}
int main()
{
int i;
char str;
begin="123456780";
beginIndex=8;
bfs();
// cout<<43434234<<endl;
while(cin>>str){
begin=str; //begin[1]='\0';
//cout<<begin<<endl;
if(begin[0] == 'x')
{
begin[0] = '0';
beginIndex = i;
}
for(i = 1; i < 9; ++i)
{
cin >> str;
begin+=str;
if(begin[i] == 'x')
{
begin[i] = '0';
beginIndex = i;
}
}
// cout<<begin<<endl;
if(mm[begin].place==0)
cout<<"unsolvable"<<endl;
else{
for(i=mm[begin].path.size()-1;i>=0;i--)
cout<<mm[begin].path[i];
cout<<endl;
}
}
return 0;
}