I'm trying to implement the Knights Tour problem in C#.
I refer to the C++ code in this link:
http://www.geeksforgeeks.org/backtracking-set-1-the-knights-tour-problem/
I've been scratching my head for hours now, trying to figure out why my c# code (which almost identical to the C++ code) doesn't produce the same result. I think I'm actually stuck in an infinite loop for some reason.
Here is the C# code:
public static int[,] exampleMat = new int[,]
{
{ -1, -1, -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1 }
};
public static int[,] directions = new int[,] { { 2, 1 },
{ 1, 2 },
{ -1, 2 },
{ -2, 1 },
{ -2, -1 },
{ -1, -2 },
{ 1, -2 },
{ 2, -1 } };
public static void KnightsTourExec(int[,] mat)
{
exampleMat[0, 0] = 0;
FindRoute(0, 0, 1, mat);
}
private static bool FindRoute(int currentX,int currentY, int times, int[,] mat)
{
if (times == 64)
return true;
for (int i = 0; i < directions.GetLength(0); i++)
{
int moveToX = currentX + directions[i, 0];
int moveToY = currentY + directions[i, 1];
bool isInMat = moveToX >= 0 && moveToX < mat.GetLength(0) && moveToY >= 0 && moveToY < mat.GetLength(1);
if(!isInMat || mat[moveToX, moveToY] != -1)
continue;
mat[moveToX,moveToY] = times;
if (FindRoute(moveToX, moveToY, times + 1, mat))
{
return true;
}
else
{
mat[moveToX, moveToY] = -1;
}
}
return false;
}
Execution in Main method:
KnightsTour.KnightsTourExec(KnightsTour.exampleMat);