Common algorithms: C # Eight Queens problem

Source: Internet
Author: User
Tags int size

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);
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.