N-Queens and N-Queens II

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

这里写图片描述
Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
 ]

N-Queens问题是回溯的典型题目了,跟数独的解法有点像。我们用path来存储可能出现的result的值,每次给新的一行中选择一个字符设为Q,然后检查其合法性。直到得到正确的解就放入result中。检查合法性的时候要检查列,左斜线和右斜线,代码如下:

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> result;
        vector<string> path(n, string(n,'.'));
        find(0, n, result, path);
        return result;
    }

    void find(int row, int n, vector<vector<string>>& result,vector<string>& path){
        if(row==n){
            result.push_back(path);
            return;
        }
        for(int col=0;col<n;col++){
            if(check(n,row,col,path)){
                path[row][col]='Q';
                find(row+1,n,result,path);
                path[row][col]='.';
            }
        }
    }

    bool check(int n, int row, int col, vector<string>& path){
        for(int i=0;i<row;i++){
            if(path[i][col]=='Q')
                return false;
        }
        for(int r=row-1, c=col-1;r>=0 && c>=0;r--,c--){
            if(path[r][c]=='Q')
                return false;
        }
        for(int r=row-1, c=col+1;r>=0 && c<n;r--,c++){
            if(path[r][c]=='Q')
                return false;
        }
        return true;
    }
};
Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

这里写图片描述

与上个题相比,这个题只是要求输出结果的个数就可以了,不需要改太多的代码,设置一个全局的变量num,当找到一个解的时候,就把num++;其他的不需要修改,便可得到结果。

class Solution {
public:
    int num;
    int totalNQueens(int n) {
        num=0;
        vector<string> path(n,string(n,'.'));
        find(0,n,path);
        return num;
    }
    void find(int row, int n , vector<string>& path){
        if(row==n)
            num++;
        for(int col=0;col<n;col++){
            if(check(row,col,n,path)){
                path[row][col]='Q';
                find(row+1,n,path);
                path[row][col]='.';
            }
        }
    }

    bool check(int row, int col, int n, vector<string>& path){
        for(int i=0;i<row;i++){
            if(path[i][col]=='Q')
                return false;
        }
        for(int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
            if(path[i][j]=='Q')
                return false;
        }
        for(int i=row-1,j=col+1;i>=0 && j<n;i--,j++){
            if(path[i][j]=='Q')
                return false;
        }
        return true;
    }
};
### 关于N皇后问题 对于给定的整数 \( n \),\( n \)-皇后问题是找到一种方法,在 \( n \times n \) 的棋盘上放置 \( n \) 个皇后,使得它们彼此之间不会互相攻击。这意味着任意两个皇后都不能位于同一行、列或对角线上。 当 \( n = 3 \) 时,可以尝试解决该问题并分析其可能性。然而,由于棋盘大小较小,实际上不存在有效的解决方案[^1]。以下是具体原因: #### 原因分析 在一个 \( 3 \times 3 \) 的棋盘上,如果要满足 \( n \)-皇后问题的要求,则需要在每一行和每一列各放一个皇后,并且这些皇后不能处于同一条对角线。通过穷举所有可能的位置组合,会发现没有任何排列能够同时满足上述条件[^2]。 为了验证这一点,可以通过编程实现回溯算法来枚举所有的潜在布局情况。下面是一个简单的 Python 实现用于展示此结论: ```python def solve_n_queens(n): def could_place(row, col): return not cols[col] and not diag1[row - col] and not diag2[row + col] def place_queen(row, col): queens.add((row, col)) cols[col] = True diag1[row - col] = True diag2[row + col] = True def remove_queen(row, col): queens.remove((row, col)) cols[col] = False diag1[row - col] = False diag2[row + col] = False def backtrack(row=0): for col in range(n): if could_place(row, col): place_queen(row, col) if row + 1 == n: output.append(queens.copy()) else: backtrack(row + 1) remove_queen(row, col) cols = [False] * n diag1 = {} diag2 = {} queens = set() output = [] backtrack() return [["."*c + "Q" + "."*(n-c-1) for (r,c) in sol] for sol in output] result = solve_n_queens(3) print(result) ``` 运行以上代码后可以看到返回的结果为空列表 `[]`,这表明确实没有可行解存在[^3]。 因此,总结来说,当 \( n = 3 \) 时,无法找到任何有效配置以完成 \( n \)-皇后挑战。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值