八皇后问题的C#解答,大家都很熟悉了,啥也不说了。看吧:
using System;
class Queen
{
const int SIZE = 8;//皇后数
public static void Main()
{
int[] Queen = new int[SIZE];//每行皇后的位置
int y, x, i, j, d, t = 0;
y = 0;
Queen[0] = -1;
while (true)
{
for (x = Queen[y] + 1; x < SIZE; x++)
{
for (i = 0; i < y; i++)
{
j = Queen[i];
d = y - i;
//检查新皇后是否与以前的皇后能相互攻击
if ((j == x) || (j == x - d) || (j == x + d))
break;
}
if (i >= y)
break;//不攻击
}
if (x == SIZE) //没有合适的位置
{
if (0 == y)
{
//回朔到了第一行
Console.WriteLine("Done");
break; //结束
}
//回朔
Queen[y] = -1;
y--;
}
else
{
Queen[y] = x;//确定皇后的位置
y++;//下一个皇后
if (y < SIZE)
Queen[y] = -1;
else
{
//所有的皇后都排完了,输出
Console.WriteLine("/n" + ++t + ':');
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
if (Queen[i] == j)
Console.Write('Q');
else
Console.Write('.');
Console.WriteLine();
Console.ReadKey();
}
y = SIZE - 1;//回朔
}
}
}
}
}