[leetcode] 51. N-Queens

Description

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.
n-queens
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

Example:

Input:

4

Output:

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

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

Explanation:

 There exist two distinct solutions to the 4-queens puzzle as shown above.

分析

题目的意思是:有n个皇后在一个棋盘上,然后皇后上下左右对角线不能共线。输出所有的放置方案。

  • 这是一个典型的递归求解的问题,下面是一个经典的做法。由于棋盘的每一排只能放一个,所以用x的下标代表棋盘的行,x的值代表列,所以用一个一维的数组递归求解就行了,节省了空间,然后递归遍历的每个位置都需要检查一下是否跟以前的皇后的位置有冲突,找一个没有冲突的位置作为当前行的皇后的位置,主要思想就是这样的。

C++实现

class Solution {
    int x[19];
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<string> out;
        string s1(n,'.');
        for(int i=0;i<n;i++){
            out.push_back(s1);
        }
        solve(res,out,0,n);
        return res;
    }
    void solve(vector<vector<string>>& res,vector<string> out,int start,int n){
        if(start==n){
            res.push_back(out);
            return ;
        }
        for(int i=0;i<n;i++){
            x[start]=i;
            out[start][i]='Q';
            if(check(start)){
                solve(res,out,start+1,n);
            }
            out[start][i]='.';
        }
    }
    bool check(int m){
        for(int i=0;i<m;i++){
            if(abs(x[m]-x[i])==abs(m-i)||x[m]==x[i]) return false;
        }
        return true;
    }
};

Python实现

实现跟上面的思路一样。

class Solution:
    def __init__(self):
    	# 下标代表行,x的值代表列
        self.x = [0]*19

    def solve(self, out, start, n, res):
        if start==n:
            res.append([''.join(item) for item in out])
            return
        for i in range(n):
            self.x[start]=i
            out[start][i]='Q'
            if self.check(start):
                self.solve(out,start+1, n, res)
            out[start][i]='.'

    def check(self, m):
        for i in range(m):
            if abs(self.x[m]-self.x[i])==abs(m-i) or self.x[m]==self.x[i]:
                return False
        return True

    def solveNQueens(self, n: int) -> List[List[str]]:
        res = []
        s = ['.']*n
        out = []
        for i in range(n):
            out.append(s[:])
        self.solve(out, 0,n, res)
        return res

参考文献

[编程题]n-queens

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值