首先感谢大神!没用大神的讲解不知道实验要怎么交代,大神代码讲解在此
- 深度优先:
#include<iostream>
#include<vector>
#include<algorithm>
#include<ctime>
using namespace std;
const int GRID = 3;
int rightPos[9] = {
0,0,0,0,0,0,0,0,0 };
int depth=10;
int sum=0;
class state{
public:
int panel [GRID][GRID];
int level;
state* parent;
state(int level) : level(level){
};
bool operator ==(state& q){
for(int i=0;i<GRID;i++){
for(int j=0;j<GRID;j++){
if(this->panel[i][j]!=q.panel[i][j])
return false;
}
}
return true;
}
state& operator =(state& p){
for(int i=0;i<GRID;i++){
for(int j=0;j<GRID;j++){
this->panel[i][j]=p.panel[i][j];
}
}
return *this;
}
};
int findZero(state st){
for(int i=0;i<GRID;i++){
for(int j=0;j<GRID;j++){
if(st.panel[i][j]==0)
return i*GRID+j;
}
}
}
int countH(state& st){
int k=0;
int h=0;
for(int i=0;i<GRID;i++){
for(int j=0;j<GRID;j++){
if(st.panel[i][j]!=rightPos[k++])
h++;
}
}
return h;
}
vector<state*>::iterator look_up_dup(vector<state*>& vec,state* p){
vector<state*>::iterator it_r=vec.begin();
for(;it_r!=vec.end();it_r++){
if((*(*it_r))==*p)
break;
}
return it_r;
}
vector<state*> open_table;
vector<state*> close_table;
void dump_panel(state* p){
for(int i=0;i<GRID;i++){
for(int j=0;j<GRID;j++){
cout<<p->panel[i][j]<<" ";
}
cout<<endl;
}
}
state* search(state& start){
int level=0;
open_table.push_back(&start);
int count=0;
while(!open_table.empty()){
state* p=open_table.back();
close_table.push_back(p);
open_table.pop_back();
if(countH(*p)==0)
return p;
if(p->level>=depth)
continue;
level=p->level+1;
int zeroPos=findZero(*p);
int x=zeroPos/3;
int y=zeroPos%3;
for(int i=0;i<4;i++){
int x_offset=0,y_offset=0;
switch(i){
case 0:x_offset=1,y_offset=0;break;
case 1:x_offset=0,y_offse