2021-1-25 八皇后问题(DFS解法)(递归)

本文介绍了八皇后问题的解决思路,通过DFS算法避免皇后之间的威胁。文章提供了一个示例输入输出,详细解释了解决方案的核心代码,包括判断函数check()和递归函数solve()。作者分享了学习过程,并希望帮助读者理解这一经典问题。
摘要由CSDN通过智能技术生成

一.例题:
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.

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

Input
In the first line, an integer k k k is given. In the following k k k lines, each square where a queen is already placed is given by two integers r r r and c c c. r r r and c c c respectively denotes the row number and the column number. The row/column numbers start with 0.

Output
Print a 8 × 8 8 \times 8 8×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…
二.解法思路:
1.二维数组表示棋盘,使用bool类型标记皇后位置,判断函数check()的返回类型为false则表示已被皇后占领位置,下一个皇后不能再放置在这里。
2.向量和pair结构体记录先前的前置条件,即输入部分,后用来记录皇后的位置 first-x,second-y。
3.利用递归的思想推进到下一行,直到8行结束。DFS核心。

三.核心代码:
1.判断函数check()的实现。

bool check(int row, int col)//形参为行和列的位置
{
   
    for (int i = 0; i < 8; i++)
    {
   
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值