8 Puzzle
8 Puzzle
h>
using namespace std;
#define N 3
struct PuzzleState {
vector<vector<int>> mat;
int x, y; // position of blank tile (0)
int cost; // total cost = g + h
int level; // g(n): number of moves from start
PuzzleState* parent;
PuzzleState(vector<vector<int>> _mat, int _x, int _y, int _newX, int _newY, int
_level, PuzzleState* _parent) {
mat = _mat;
swap(mat[_x][_y], mat[_newX][_newY]);
x = _newX;
y = _newY;
level = _level;
parent = _parent;
cost = INT_MAX; // Will be updated later
}
};
while(!pq.empty()) {
PuzzleState* min = pq.top();
pq.pop();
if(min->cost == 0) {
cout << "Solved in " << min->level << " steps!" << endl;
printPath(min);
return;
}
if(isValid(newX, newY)) {
PuzzleState* child = new PuzzleState(min->mat, min->x, min->y,
newX, newY, min->level + 1, min);
child->cost = calculateCost(child->mat);
pq.push(child);
}
}
}
}
int main() {
vector<vector<int>> initial(3, vector<int>(3));
int x, y;
cout << "Enter the initial 3x3 puzzle (use 0 for blank tile):\n";
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++) {
cin >> initial[i][j];
if(initial[i][j] == 0) {
x = i;
y = j;
}
}
solve(initial, x, y);
return 0;
}