八皇后问题 [OpenJ_Bailian-2698]

版权声明:菜鸟一枚~~ 有想法可在下面评论, 转载标明出处即可。 https://blog.csdn.net/KLFTESPACE/article/details/82054984

在国际象棋棋盘上放置八个皇后,要求每两个皇后之间不能直接吃掉对方。

Input

无输入。

Output

按给定顺序和格式输出所有八皇后问题的解(见Sample Output)。

Sample Input

 

Sample Output

No. 1
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 
No. 2
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 1 0 0 0 0 0 
No. 3
1 0 0 0 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
No. 4
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 0 0 0 0 1 0 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
No. 5
0 0 0 0 0 1 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 0 1 
0 0 1 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 1 0 0 0 0 
No. 6
0 0 0 1 0 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 7
0 0 0 0 1 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 1 
0 0 0 1 0 0 0 0 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 8
0 0 1 0 0 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 0 0 1 0 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
No. 9
0 0 0 0 1 0 0 0 
1 0 0 0 0 0 0 0 
0 0 0 1 0 0 0 0 
0 0 0 0 0 1 0 0 
0 0 0 0 0 0 0 1 
0 1 0 0 0 0 0 0 
0 0 0 0 0 0 1 0 
0 0 1 0 0 0 0 0 
...以下省略

Hint

此题可使用函数递归调用的方法求解。

扫描二维码关注公众号,回复: 2993134 查看本文章

这道题在judge上出现了问题。 然后就是bfs回溯问题。。。

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
int n=8;
int a[10][10] = { 0 };
int t = 1;
void print()
{
    printf("No. %d\n", t++);
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            printf("%d ", a[j][i]);
        }
        printf("\n");
    }
}
bool judge(int x, int y)
{
    for(int i=0; i<x; i++)
    {//竖直方向||左上方 || 右上方
        if(a[i][y] || (y-i-1>=0 && a[x-i-1][y-i-1]) || (y+i+1<8 && a[x-i-1][y+i+1]))
            return false;
     }
    return true;
}
/*
void dfs(int num)
{
    if (num >= 8){
        print();
    }
    for (int i = 0; i < 8; i++)
    {
       if (a[num][i]!=1&&judge(num, i))
        {
            a[num][i] = 1;
            dfs(num + 1);
            a[num][i] = 0;
        }

    }

}
*/

int dfs(int num)
{
    if (num >= 8){
        print();
    }
    for (int i = 0; i < 8; i++)
    {
        hang[num] = i;
        if (a[num][i]!=1&&judge(num, i))
        {
            a[num][i] = 1;
            if(dfs(num + 1))
                return 1;
            a[num][i] = 0;
        }

    }
return 0;
}
int main()
{
        dfs(0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/KLFTESPACE/article/details/82054984