8 Queens Problem (八皇后问题)

The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure.

8 Queens Problem (八皇后问题)_第1张图片

 

For a given chess board where kk queens are already placed, find the solution of the 8 queens problem.

Input

In the first line, an integer kk is given. In the following kk lines, each square where a queen is already placed is given by two integers rr and cc. rr and ccrespectively denotes the row number and the column number. The row/column numbers start with 0.

Output

Print a 8×88×8 chess board by strings where a square with a queen is represented by 'Q' and an empty square is represented by '.'.

Constraints

  • There is exactly one solution

Sample Input 1

2
2 2
5 3

Sample Output 1

......Q.
Q.......
..Q.....
.......Q
.....Q..
...Q....
.Q......
....Q...

 题意:在棋盘上放置8个皇后,使得他们互不攻击,每个皇后的攻击范围为同行同列和同对角线,求出其解。

题解:

            在第一行的任意位置摆放皇后
            在第二行中,选择不会被第一行皇后攻击的格子摆放第二个皇后

            前i行放好i个皇后且保证他们不会相互攻击,

            在第(i+1)行寻找不会被任意一个皇后攻击的格子,

            摆放第(i+1)个皇后。
           如果不存在满足的条件,则返回上一行寻找下一个不会被攻击到的格子。。。。

//斜向左下方i+j
//斜向右下方i-j+n-1
#include
#include
#include
#include
using namespace std;
int r[8],l[8],xz[20],xy[20];
bool book[10][10];
void init()
{
    for(int i=0;i<8;i++)
    {
        r[i]=-1;
        l[i]=-1;
    }
    for(int i=0;i<15;i++)
    {
        xz[i]=-1;
        xy[i]=-1;
    }
}
void print()
{
    for(int i=0;i<8;i++)
    {
        for(int j=0;j<8;j++)
        {
            if(book[i][j])
            {
                if(r[i]!=j)
                    return ;
            }
        }
    }
    for(int i=0;i<8;i++)
    {
        for(int j=0;j<8;j++)
        {
            if(r[i]==j)
                printf("Q");
            else
                printf(".");
        }
        printf("\n");
    }
}
void check(int h)
{
    if(h==8)
    {
        print();
        return;
    }
    for(int j=0;j<8;j++)
    {
        if(l[j]==1||xz[h+j]==1||xy[h-j+7]==1)
            continue;
        else
        {
            r[h]=j;
            l[j]=1;
            xz[h+j]=1;
            xy[h-j+7]=1;
        }
        check(h+1);//下一行
        r[h]=l[j]=xz[h+j]=xy[h-j+7]=-1;
    }
}
int main()
{
    init();
    memset(book,0,sizeof(book));
    int k;
    scanf("%d",&k);
    for(int i=0;i

 

你可能感兴趣的:(启发式搜索)