#include <bits/stdc++.
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
}
};
// Final Goal State
vector<vector<int>> goal = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 0}
};
// Directions (up, down, left, right)
int dx[] = { -1, 1, 0, 0 };
int dy[] = { 0, 0, -1, 1 };
// Heuristic: Manhattan Distance
int calculateCost(vector<vector<int>> mat) {
int cost = 0;
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
if(mat[i][j] != 0) {
int value = mat[i][j];
int targetX = (value - 1) / N;
int targetY = (value - 1) % N;
cost += abs(i - targetX) + abs(j - targetY);
}
return cost;
}
// Check if position is valid
bool isValid(int x, int y) {
return (x >= 0 && x < N && y >= 0 && y < N);
}
// Print the 3x3 matrix
void printMatrix(vector<vector<int>> mat) {
for(auto row : mat) {
for(int val : row)
cout << val << " ";
cout << endl;
}
cout << "-----------" << endl;
}
// Comparator for priority queue
struct comp {
bool operator()(PuzzleState* lhs, PuzzleState* rhs) {
return (lhs->cost + lhs->level) > (rhs->cost + rhs->level);
}
};
// Print the path from root to goal
void printPath(PuzzleState* root) {
if (root == NULL) return;
printPath(root->parent);
printMatrix(root->mat);
}
void solve(vector<vector<int>> initial, int x, int y) {
priority_queue<PuzzleState*, vector<PuzzleState*>, comp> pq;
PuzzleState* root = new PuzzleState(initial, x, y, x, y, 0, NULL);
root->cost = calculateCost(initial);
pq.push(root);
while(!pq.empty()) {
PuzzleState* min = pq.top();
pq.pop();
if(min->cost == 0) {
cout << "Solved in " << min->level << " steps!" << endl;
printPath(min);
return;
}
// Explore all 4 directions
for(int i = 0; i < 4; i++) {
int newX = min->x + dx[i];
int newY = min->y + dy[i];
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;
}