LeetCode 刷题记录 51. N-Queens

题目:
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.

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.
解法同LeetCode 刷题记录52. N-Queens II中的解法1一直,只要我们在对应皇后的位置直接变为‘Q’
c++:
c++直接可以初始化一个n*n为’.‘的列表,然后遍历这个列表在对应位置变为’Q’
注意我们下标是从1开始的,注意对应的要减一

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        vector<int> pos(n+1,0);
        dfs(pos , 1 ,n ,res);
        return res;
    }
    void dfs(vector<int>& pos, int row, int n,vector<vector<string>>& res){
        if(row == n + 1){
            vector<string> path(n, string(n,'.'));
            for(int i = 1; i <= n; i++){
                path[i-1][pos[i] - 1] = 'Q';
            }
            res.push_back(path);
            
            return;
        }
        for(int col = 1; col <= n; col++){
            if(!isVaild(pos,row,col)) continue;
            pos[row] = col;
            dfs(pos,row + 1,n,res);
            pos[row] = 0;
        }
    }
    bool isVaild(vector<int>& pos, int row, int col){
        for(int i = 1; i < row; i++){
            if(col == pos[i] || abs(row - i) == abs(col - pos[i])){
                return false;
            }
        }
        return true;
    }
};

java:
java不能直接生成n*n为’.'的列表,所以我们依次生成每行

class Solution {
    public List<List<String>> solveNQueens(int n) {
        int[] pos = new int[n+1];
        List<List<String>> res = new ArrayList<>();
        dfs(pos , 1 ,n,res);
        return res;
    }
     private void dfs(int[] pos, int row, int n, List<List<String>> res){
        if(row == n + 1){
            List<String> path= new ArrayList<>();
            for(int i = 1; i <= n; i++){
                char[] t = new char[n];
                Arrays.fill(t,'.');
                t[pos[i] - 1] = 'Q';
                path.add(new String(t));
                
            }
            res.add(path);
            
            return;
        }
        for(int col = 1; col <= n; col++){
            if(!isVaild(pos,row,col)) continue;
            pos[row] = col;
            dfs(pos,row + 1,n,res);
            pos[row] = 0;
        }
    }
    private boolean isVaild(int[] pos, int row, int col){
        for(int i = 1; i < row; i++){
            if(col == pos[i] || Math.abs(row - i) == Math.abs(col - pos[i])){
                return false;
            }
        }
        return true;
    }
}

python:
用[’.’ * q + ‘Q’ + ‘.’ * (n - q - 1) for q in pos]语句生成每一种情况,遍历每一行的位置q,每一行应该有q 个’.‘加’Q’再加q 个’.’ (n - q - 1)

class Solution(object):
    def solveNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        res = []
        pos = [-1] * n
        self.dfs(pos , 0 ,n,res)
        return res
    def dfs(self, pos, row, n,res):
        if row == n:
            
            res.append(['.' * q + 'Q' + '.' * (n - q - 1) for q in pos]);
            return
        
        for col in xrange(n): 
            if not self.isVaild(pos,row,col): continue
            pos[row] = col
            self.dfs(pos,row + 1,n,res)
            pos[row] = -1
        
    def isVaild(self,pos, row, col):
        for i in xrange(row):
            if col == pos[i] or abs(row - i) == abs(col - pos[i]):
                return False
            
        
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值