我试图在C#中实施Knights Tour问题。
我在这个链接中引用了C ++代码:
http://www.geeksforgeeks.org/backtracking-set-1-the-knights-tour-problem/
我现在已经摸不着头脑了几个小时,试图找出为什么我的c#代码(几乎与C ++代码完全相同)并没有产生相同的结果。我想我出于某种原因实际上陷入了无限循环。
这是C#代码:
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;
}
在Main方法中执行:
KnightsTour.KnightsTourExec(KnightsTour.exampleMat);