如何用C++中的广度优先搜索解决8题 我想用C++程序构建一个C++程序,用BFS解决8个难题。 我想显示每个生成的状态。 但问题是,我不知道如何生成状态。 我只想要一些干净的函数,它将有效地生成状态,并且将有一个探索的数组,它将确保没有冗余状态
我已经探索过GitHub,但是有太多复杂的解决方案 到目前为止,我已经编写了以下代码如何用C++中的广度优先搜索解决8题 我想用C++程序构建一个C++程序,用BFS解决8个难题。 我想显示每个生成的状态。 但问题是,我不知道如何生成状态。 我只想要一些干净的函数,它将有效地生成状态,并且将有一个探索的数组,它将确保没有冗余状态,c++,breadth-first-search,sliding-tile-puzzle,C++,Breadth First Search,Sliding Tile Puzzle,我已经探索过GitHub,但是有太多复杂的解决方案 到目前为止,我已经编写了以下代码 #include<iostream> #include<conio.h> using namespace std; class puzzle{ private: int initial[3][3],goal[3][3] = {{1,2,3},{4,5,6},{7,8,0}}; int queue[1000]; string data
#include<iostream>
#include<conio.h>
using namespace std;
class puzzle{
private:
int initial[3][3],goal[3][3] = {{1,2,3},{4,5,6},{7,8,0}};
int queue[1000];
string data;
public:
void genratePuzzle();
void showState();
bool check_goal(int initial);
};
void puzzle::genratePuzzle(){
cout<<"\n***Create initial state 0-8***\n";
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cout<<"Insert at ["<<i<<"]["<<j<<"] : ";
cin>>initial[i][j];
}
}
}
void puzzle::showState(){
cout<<"\n***State***\n";
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cout<<initial[i][j]<<" ";
}
cout<<endl;
}
}
bool puzzle::check_goal(int initial){
bool check = true;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(initial[i][j] != goal[i][j]){
check = false;
}
}
}
return check;
}
int main(){
puzzle p1;
p1.genratePuzzle();
p1.showState();
getch();
}
使你的州陷入困境
struct state {
int data[3][3];
bool operator < (const state & other) {
for (int y=0; y<3; ++y) {
for (int x=0; x<3; ++x) {
if (data[y][x] < other.data[y][x]) {
return true;
}
if (data[y][x] > other.data[y][x]) {
return false;
}
}
}
return false; // all were equal
}
}
如何生成新的状态?您从一个现有状态开始,然后在该状态上尝试所有有效的移动。重复操作直到完成。为您的状态声明类型的基本原则是好的。考虑STD::状态内的数组。考虑STD::探索的unOrdEdTy集可能需要编写哈希函数,但FIFORAL9非常小,因此无法获得冲突。
struct state {
int data[3][3];
bool operator < (const state & other) {
for (int y=0; y<3; ++y) {
for (int x=0; x<3; ++x) {
if (data[y][x] < other.data[y][x]) {
return true;
}
if (data[y][x] > other.data[y][x]) {
return false;
}
}
}
return false; // all were equal
}
}
state a;
// do something to the state...
// and you can do this
explored[a] = true;