N-Queens

一. 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.

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

[
[“.Q..”, // Solution 1
“…Q”,
“Q…”,
“..Q.”],

[“..Q.”, // Solution 2
“Q…”,
“…Q”,
“.Q..”]
]

Difficulty:Hard

TIME:40MIN

解法

N皇后问题也是搜索的经典问题,但是论复杂度来说,Sudoku Solver会稍微难一点。因此如果会解决数独,那么这道题也就没什么特别大的问题。

首先,这道题不像数独需要每次取最可能的点才是最优的搜索路线,而这道题如果每行从左到右依次搜索,其实就是最优的搜索路线了。而且考虑的问题也比较简单,就是能不能放的问题(true和false的问题),不像数独会考虑0-9几种情况。

不过就算是true和false的问题,由于考虑到回溯的原因,还是采用递增递减的策略比较好(如果该位置不能填则加一,回溯的时候减一,等于0说明可以填),这样就不会在回溯的时候无法准确还原搜索之前棋盘的样貌。

void dfs(vector<vector<string>> &result, vector<string> &v, vector<vector<int>> &m, int index) {
    if(index == v.size()) {
        result.push_back(v);
        return;
    }
    for(int i = 0; i < v.size(); i++) {
        if(m[index][i] == 0) {
            v[index][i] = 'Q';
            for(int j = 0; j + index + 1 < v.size(); j++) {
                m[j + index + 1][i]++;
                if(i - j - 1 >= 0)
                    m[j + index + 1][i - j - 1]++;
                if(i + j + 1 < v.size())
                    m[j + index + 1][i + j + 1]++;
            }
            dfs(result, v, m, index + 1);
            //还原棋盘,由于之前以为单纯true和false就可以,导致无法准确还原棋盘样貌
            for(int j = 0; j + index + 1 < v.size(); j++) {
                m[j + index + 1][i]--;
                if(i - j - 1 >= 0)
                    m[j + index + 1][i - j - 1]--;
                if(i + j + 1 < v.size())
                    m[j + index + 1][i + j + 1]--;
            }
            v[index][i] = '.';
        }
    }
}
vector<vector<string>> solveNQueens(int n) {
    vector<vector<string>> result;
    vector<string> v(n,string(n,'.'));
    vector<vector<int>> m(n, vector<int>(n, 0)); //取一个数组用来递增递减,判断能否填入
    dfs(result, v, m, 0);
    return result;
}

代码的时间复杂度不大于 O(n!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用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`函数求解四皇后问题。最后输出结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值