-3

I want to build a c++ program that would solve 8-puzzle problem using BFS. I want to show every generated state. But the problem is, I don't know how to generate state. I just want some clean function which will efficiently generate states and there will be a Explored array which will assure that there is no redundant state.

I've explored GitHub but there is too much complex solutions

I've written the following code till now

#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();
}

Goal state

1 2 3

4 5 6

7 8 0

1 Answers1

0

Put your state into

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
    }
}

Now you can use values of type state as keys in a std::map e.g. make a std::map<state, bool> explored if you want. It behaves like an array indexed by states, so:

state a;
// do something to the state...

// and you can do this
explored[a] = true;

How do you generate new states? You start with an existing state and try all valid moves on it. Repeat until done.

  • The basic principle of "declare a type" for your state is good. Consider std::array within the state. Consider std::unordered_set for explored (will probably need to write a hash function, but factorial(9) is pretty small so no collisions is obtainable) – Kenny Ostrom May 18 '19 at 21:11