Knights Tour の問題を C# で実装しようとしています。
このリンクの 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);