The
Eight Queens problem is an old and famous problem, a typical application of backtracking algorithms. The eight Queens problem is the 8 queens on the chessboard. There are 92 solutions in the 8!=40320 arrangement in the same row, column, or Slash. The code is as follows:
using System;
using System.Collections.Generic;
using System.Text;
Namespace Exqueen
{
class Queen
{
public void queenarithmetic (int size)
{
int[] Queen = new int[size];//the position of each row queen
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;
//Check if the new queen can attack each other with the former Queen
if ((j = = x) | | (j = = x-d) | | (j = = x + d))
break;
}
if (i >= y)
break;//not attack
}
if (x = size)//No Appropriate location
{
if (0 = y)
{
//back to first line
Console.wri Teline ("over");
break;//End
}
//Back up
queen[y] = -1;
y--;
}
Else
{
Queen[y] = x;//Determine the location of the Queen
y++;//next Queen
if (Y < size)
Queen[y] =-1;
else
{
//All queens are finished, output
Console.WriteLine ("\ n" + ++t + ': ');
for (i = 0; i < size; i++)
{
for (j = 0; J < size; J +)
Console.Write (Queen[i] = j? ' Q ': ' * ');
Console.WriteLine ();
}
y = size-1;//back
}
}
}
}
public static VO ID Main ()
{
int size = 8;//Queen number
Queen q = new Queen ();
q.queenarithmetic (size);
}
}
}