我正在尝试在 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);