利用回溯算法求解,话不多说直接上代码~
private static int max = 8; //设置棋盘大小
private static int count = 0;
private static int judgeCount = 0;
private static int[] array = new int[max];
public static void ChessBoardPrint()
{
Check(0);
Console.WriteLine("解法共" + count + "种");
}
public static void Check(int n)
{
if (n == max)
{
count++;
PrintArray();
return;
}
for (int i = 0; i < max; i++)
{
array[n] = i;
if (Judge(n))
{
Check(n + 1);
}
}
}
public static bool Judge(int n)
{
judgeCount++;
for (int i = 0; i < n; i++)
{
if (array[i] == array[n] || Math.Abs(n - i) == Math.Abs(array[i] - array[n]))
{
return false;
}
}
return true;
}
public static void PrintArray()
{
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < max; j++)
{
if (array[i] == j)
{
Console.Write(" 1 ");
}
else {
Console.Write(" - ");
}
}
Console.WriteLine();
}
Console.WriteLine("***********************************");
}
网友评论