using
System;
using
System.Collections.Generic;
class
GFG
{
public
static
int
N = 3;
public
class
Node
{
public
Node parent;
public
int
[,] mat =
new
int
[N, N];
public
int
x, y;
public
int
cost;
public
int
level;
}
public
static
void
PrintMatrix(
int
[,] mat)
{
for
(
int
i = 0; i < N; i++)
{
for
(
int
j = 0; j < N; j++)
{
Console.Write(mat[i, j] +
" "
);
}
Console.WriteLine();
}
}
public
static
Node NewNode(
int
[,] mat,
int
x,
int
y,
int
newX,
int
newY,
int
level, Node parent)
{
Node node =
new
Node();
node.parent = parent;
node.mat =
new
int
[N, N];
for
(
int
i = 0; i < N; i++)
{
for
(
int
j = 0; j < N; j++)
{
node.mat[i, j] = mat[i, j];
}
}
int
temp = node.mat[x, y];
node.mat[x, y] = node.mat[newX, newY];
node.mat[newX, newY] = temp;
node.cost =
int
.MaxValue;
node.level = level;
node.x = newX;
node.y = newY;
return
node;
}
public
static
int
[] row = { 1, 0, -1, 0 };
public
static
int
[] col = { 0, -1, 0, 1 };
public
static
int
CalculateCost(
int
[,] initialMat,
int
[,] finalMat)
{
int
count = 0;
for
(
int
i = 0; i < N; i++)
{
for
(
int
j = 0; j < N; j++)
{
if
(initialMat[i, j] != 0 && initialMat[i, j] != finalMat[i, j])
{
count++;
}
}
}
return
count;
}
public
static
int
IsSafe(
int
x,
int
y)
{
return
(x >= 0 && x < N && y >= 0 && y < N) ? 1 : 0;
}
public
static
void
PrintPath(Node root)
{
if
(root ==
null
)
{
return
;
}
PrintPath(root.parent);
PrintMatrix(root.mat);
Console.WriteLine();
}
public
class
Comp : IComparer<Node>
{
public
int
Compare(Node lhs, Node rhs)
{
return
(lhs.cost + lhs.level) > (rhs.cost + rhs.level) ? 1 : -1;
}
}
public
static
void
Solve(
int
[,] initialMat,
int
x,
int
y,
int
[,] finalMat)
{
var
pq =
new
SortedSet<Node>(
new
Comp());
Node root = NewNode(initialMat, x, y, x, y, 0,
null
);
root.cost = CalculateCost(initialMat, finalMat);
pq.Add(root);
while
(pq.Count > 0)
{
Node min = pq.Min;
pq.Remove(min);
if
(min.cost == 0)
{
PrintPath(min);
return
;
}
for
(
int
i = 0; i < 4; i++)
{
if
(IsSafe(min.x + row[i], min.y + col[i]) > 0)
{
Node child = NewNode(min.mat, min.x, min.y, min.x + row[i], min.y + col[i], min.level + 1, min);
child.cost = CalculateCost(child.mat, finalMat);
pq.Add(child);
}
}
}
}
public
static
void
Main(
string
[] args)
{
int
[,] initialMat =
{
{1, 2, 3},
{5, 6, 0},
{7, 8, 4}
};
int
[,] finalMat =
{
{1, 2, 3},
{5, 8, 6},
{0, 7, 4}
};
int
x = 1, y = 2;
Solve(initialMat, x, y, finalMat);
}
}