我一直在尝试使用回溯来解决Knight's tour问题。这是我的代码: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
int[,] arr = new int[8, 8];
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
arr[i, j] = -1;
}
// Console.WriteLine();
}
arr[0, 0] = 0;
knightTour(arr, 0, 0, 0, 63);
printArray(arr);
}
private static void knightTour(int[,] arr, int x, int y, int move, int empty)
{
if (empty <= 0)
{
printArray(arr);
Console.WriteLine("--------------------------------------------");
}
else
{
//int movelocal = move;
int temp = 0;
if (isavailable(arr, x + 2, y + 1))
{
temp = arr[x + 2, y + 1];
arr[x + 2, y + 1] = move + 1;
knightTour(arr, x + 2, y + 1, move + 1, empty - 1);
arr[x + 2, y + 1] = temp;
}
if (isavailable(arr, x - 2, y + 1))
{
temp = arr[x - 2, y + 1];
arr[x - 2, y + 1] = move + 1;
knightTour(arr, x - 2, y + 1, move + 1, empty - 1);
arr[x - 2, y + 1] = temp; //backtrack
}
if (isavailable(arr, x - 1, y + 2))
{
temp = arr[x - 1, y + 2];
arr[x - 1, y + 2] = move + 1;
knightTour(arr, x - 1, y + 2, move + 1, empty - 1);
arr[x - 1, y + 2] = temp;
}
if (isavailable(arr, x + 1, y + 2))
{
temp = arr[x + 1, y + 2];
arr[x + 1, y + 2] = move + 1;
knightTour(arr, x + 1, y + 2, move + 1, empty - 1);
arr[x + 1, y + 2] = temp;
}
if (isavailable(arr, x + 2, y - 1))
{
temp = arr[x + 2, y - 1];
arr[x + 2, y - 1] = move + 1;
knightTour(arr, x + 2, y - 1, move + 1, empty - 1);
arr[x + 2, y - 1] = temp;
}
if (isavailable(arr, x - 2, y - 1))
{
temp = arr[x - 2, y - 1];
arr[x - 2, y - 1] = move + 1;
knightTour(arr, x - 2, y - 1, move + 1, empty - 1);
arr[x - 2, y - 1] = temp;
}
if (isavailable(arr, x + 1, y - 2))
{
temp = arr[x + 1, y - 2];
arr[x + 1, y - 2] = move + 1;
knightTour(arr, x + 1, y - 2, move + 1, empty - 1);
arr[x + 1, y - 2] = temp;
}
if (isavailable(arr, x - 1, y - 2))
{
temp = arr[x - 1, y - 2];
arr[x - 1, y - 2] = move + 1;
knightTour(arr, x - 1, y - 2, move + 1, empty - 1);
arr[x - 1, y - 2] = temp;
}
}
}
private static bool isavailable(int[,] arr, int x, int y)
{
if (x < 8 && x >= 0 && y < 8 && y >= 0 && arr[x, y] == -1)
{
return true;
}
else
{
return false;
}
}
private static void printArray(int[,] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j]);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}`
它是一种简单的回溯方法,在8个可用的移动中,我遍历其中一个并查看它是否会导致解决方案。如果它没有,那么我回到我之前的状态并尝试剩余的动作。 该程序继续在递归中运行,从不陷入基本情况。有人帮我找到错误吗?