N-Queens

题目

The n-queens puzzle is the problem of placing n queens on an nn 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.."]
]

思路

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int>> result;
        vector<int> vec;
        myqueens(result,vec,n,1);  
        vector<vector<string>>  res;
        for(int i=0;i<result.size();i++)
        {
            vec = result[i];
            vector<string> tmpvec;
            for(int j=0;j<n;j++)
            {
                string tmpstr(n,'.');
                tmpstr[vec[j]-1] = 'Q';
                tmpvec.push_back(tmpstr);               
            }
            res.push_back(tmpvec);        
        }                
        return res;  
    }  
      
    void myqueens(vector<vector<int>> &result, vector<int> &vec, int n, int k)  
    {  
        if(k==n+1){  
            result.push_back(vec);
            return ;  
        }  
        int j=1;  
        for(j=1;j<=n;j++){  
            if(isCanloc(vec, k, j)){     
                vec.push_back(j);  
                myqueens(result, vec, n, k+1);  
                vec.pop_back();  
            }  
        }       
        if(j>n)  
            return ;  
    }   
      
    bool isCanloc(vector<int> &vec, int k, int j){  
        for(int i=0;i<vec.size();i++)  
        {  
            int x = i+1;  
            int y = vec[i];  
            if(j==y || k-x==j-y || x-k==j-y)  
                return false;  
        }  
        return true;  
    }              
}; 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用ABT算法求解四皇后问题的Python代码: ``` def is_valid(board, row, col): for i in range(row): if board[i] == col or \ board[i] - i == col - row or \ board[i] + i == col + row: return False return True def backtrack(board, row, n): if row == n: return True for col in range(n): if is_valid(board, row, col): board[row] = col if backtrack(board, row + 1, n): return True return False def asynchronous_backtracking(position, domains, n): if len(position) == n: return position var = max(domains, key=lambda x: len(domains[x])) for val in domains[var]: pos_copy = position.copy() domains_copy = {k: v.copy() for k, v in domains.items()} pos_copy[var] = val domains_copy[var] = {val} if all(len(domains_copy[k]) > 0 for k in domains_copy): if backtrack(pos_copy, 0, n): result = asynchronous_backtracking(pos_copy, domains_copy, n) if result is not None: return result return None n = 4 position = {i: None for i in range(n)} domains = {i: set(range(n)) for i in range(n)} result = asynchronous_backtracking(position, domains, n) print(result) ``` 该代码首先定义了一个`is_valid`函数,用于检查当前位置是否合法。然后定义了一个普通的回溯算法函数`backtrack`,用于求解N皇后问题。最后定义了一个使用ABT算法的函数`asynchronous_backtracking`,该函数从所有未赋值的变量中选择一个具有最小剩余值的变量,然后对该变量的每个可能值进行尝试,直到找到一个可行解或无法继续搜索为止。 在主程序中,将变量和其域初始化为字典,然后调用`asynchronous_backtracking`函数求解四皇后问题。最后输出结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值