参考
1.http://www.cnblogs.com/goodness/archive/2010/05/04/1727141.html 八数码的八境界
2.https://www.cnblogs.com/zufezzt/p/5659276.html HDU 1043 八数码(八境界)
以下仅为个人理解,不能保证正确
境界1:暴力广搜+STL(HDU1043 G++ 爆内存 C++ 1248ms 32568kb AC)
说实话这个能过真的是太秀了鬼鬼,差200kb就爆炸
由于八数码的状态总共也就9!=362880,所以完全可以采用set判重,string存储状态,map存储到终态需要的步数
int dy[4]={-1,1,0,0};
int dx[4]={
0,0,-1,1};
string dir="durl";
set<string> f;
map<string,string> m;
从最终状态开始”12345678x”,倒着记录
m["12345678x"]="";
f.insert("12345678x");
然后就是bfs咯
代码如下:
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<bitset>
#include<iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAX_N=100000;
const int INF = 0x3f3f3f3f;
#define eps 1e-7
short dy[4]={-1,1,0,0};
short dx[4]={
0,0,-1,1};
string dir="durl";//这里方向和题中给的要反一下哦
set<string> f;
map<string,string> m;
struct node{
string s;
string path;
int pos;
node(){}
node(string str,string pa,int Pos){
s=str;
path=pa;
pos=Pos;
}
};
void pre(){
queue<node> q;
q.push(node("12345678x","",8));
m["12345678x"]="";
f.insert("12345678x");
while(!q.empty()){
node h=q.front();
q.pop();
short a=h.pos/3;//模拟一下上下左右
short b=h.pos%3;
for(int i=0;i<4;i++){
short y=a+dy[i];
short x=b+dx[i];
if(y<0||y>2||x<0||x>2)//判断是否在范围内
continue;
short pos=3*y+x;
swap(h.s[h.pos],h.s[pos]);
if(f.find(h.s)==f.end()){
//使用set进行判重
q.push(node(h.s,dir[i]+h.path,pos));
f.insert(h.s);
m[h.s]=dir[i]+h.path;
}
swap(h.s[h.pos],h.s[pos]);//这里在记录完后需要再转回来 假装什么都没发生
}
}
}
int main(){
ios::sync_with_stdio(false);
pre();
char input;
while(cin>>input){
//由于输入间存在好几个空格,所以如果用scanf注意输入格式
string v="";
v=v+input;
for(short i=1;i<=8;i++){
cin>>input;
v=v+input;
}
if(m[v]==""&&v!="12345678x")//由于给出状态即是最终态所以没有步数,需要与无解的情况分别一下
cout<<"unsolvable"<<endl;
else
cout<<m[v]<<endl;
}
return 0;
}
这个差点爆炸,不过挑战上面广搜的一道练习题可以练习这一部分:Aizu - 0121(AOJ) 七数码问题
解法和上面的思路完全一样
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAX_N=100000;
const int INF = 0x3f3f3f3f;
#define eps 1e-7
map<string , int > m;
int dir[4]={-4,4,-1,1};
void bfs(){
queue<string> q;
m["01234567"]=1;
q.push("01234567");
while(!q.empty()){
string t=q.front();
q.pop();
int pi;
for(int i=0;i<8;i++){
if(t[i]=='0'){
pi=i;
break;
}
}
for(int i=0;i<4;i++){
if(pi==4&&i==2)
continue;