n皇后 最快算法

这是一种状态压缩 dp
1、 求 n 皇后总数

class Solution {
public:
    int upperlimit = 0;
    int sum = 0;
	
	/*
		从第一行开始能放的位置, 并置为 1
		now 记录了当前哪些列放了皇后
		ld 记录了 45 度方向放皇后的列
		rd 记录了 135 度方向放皇后的列
	*/
    void test(int now, int left, int right) {
        if (now == upperlimit) {
            ++sum;
            return;
        }
        if (now != upperlimit) {
        	// 找到当前行哪些列可放皇后
            int pos  = upperlimit &  ~ (now | left | right);
            while (pos) {
            	// 找到最右的位置
                int  p = pos & -pos;
                //将当前列置为 1, 递归寻找下一行
                test(now ^ p, (left ^ p) << 1, (right ^ p) >> 1);
                pos -= p;
            }
        }
    }

    int totalNQueens(int n) {
        upperlimit = (1 << n) - 1;
        sum = 0;
        test(0, 0, 0);
        return sum;
    }
};
  1. 求有哪些 n 皇后
/*
 * @lc app=leetcode.cn id=51 lang=cpp
 *
 * [51] N 皇后
 */
#include <iostream>
#include <utility>
#include <string>
#include <string.h>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>

using namespace std;

// @lc code=start
class Solution {
public:
    bool valid(vector<string>& temp, int x, int y) {
        // 列
        for (int i = 0; i < x; ++i) {
            if (temp[i][y] == 'Q') {
                return false;
            }
        }
        // 45°
        int nx = x - 1, ny = y + 1;
        while (nx >= 0 && ny < temp[0].size()) {
            if (temp[nx][ny] == 'Q') {
                return false;
            }
            nx = nx - 1;
            ny = ny + 1;
        }

        // 135°
        nx = x - 1, ny = y - 1;
        while (nx >= 0 && ny >= 0) {
            if (temp[nx][ny] == 'Q') {
                return false;
            }
            nx = nx - 1;
            ny = ny - 1;
        }
        return true;
    }

    void backtracking(vector<vector<string>>& ans, vector<string>& temp, int row) {
        if (row >= temp.size()) {
            ans.push_back(temp);
            return;
        }
        for (int i = 0; i < temp[0].size(); ++i) {
            if (valid(temp, row, i)) {
                temp[row][i] = 'Q';
                backtracking(ans, temp, row + 1);
                temp[row][i] = '.';
            }
        }
    }
	
	/*
		一般回溯寻找
	*/
    vector<vector<string>> solveNQueens1(int n) {
        vector<string> temp(n, string(n, '.'));
        vector<vector<string>> ans;
        backtracking(ans, temp, 0);
        return ans;
    }
	
    void backtracking_plus(vector<vector<string>>& ans, vector<string>& temp, int i, int now, int ld, int rd, int upperlimt) {
        if (now == upperlimt) {
            ans.push_back(temp);
            return;
        }
        int pos = upperlimt & ~(now | ld | rd);
        while (pos) {
            int p = pos & ~(pos - 1);
            pos -= p;
            int index = log2(p);
            temp[i][index] = 'Q';
            backtracking_plus(ans, temp, i + 1, now ^ p, (ld ^ p) << 1, (rd ^ p) >> 1, upperlimt);
            temp[i][index] = '.';
        }
    }
	
	/*	
		优化回溯算法
	*/
    vector<vector<string>> solveNQueens(int n) {
        vector<string> temp(n, string(n, '.'));
        vector<vector<string>> ans;
        backtracking_plus(ans, temp,0, 0, 0, 0, pow(2, n) - 1);
        return ans;
    }
};
// @lc code=end

int main() {
    auto data = Solution{}.solveNQueens(6);
    for (auto& strvec : data) {
        for (auto& str : strvec) {
            cout << str << endl;
        }
        cout << endl;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
n皇后问题是一个经典的回溯算法问题,其时间复杂度不可避免的是指数级别的,因此不存在快速解法。 下面给出一个常规的n皇后问题的回溯算法实现示例,该实现使用了一个大小为n的一维数组来记录每行所放置的皇后所在列的位置,具体实现如下: ``` #include <iostream> #include <vector> using namespace std; void n_queens(int n, vector<int>& queens, vector<vector<int>>& result) { if (queens.size() == n) { result.push_back(queens); return; } for (int i = 0; i < n; i++) { bool flag = true; for (int j = 0; j < queens.size(); j++) { if (queens[j] == i || abs(queens[j] - i) == abs(j - queens.size())) { flag = false; break; } } if (flag) { queens.push_back(i); n_queens(n, queens, result); queens.pop_back(); } } } int main() { int n = 8; // 设置棋盘大小n vector<int> queens; vector<vector<int>> result; n_queens(n, queens, result); cout << "Total solutions: " << result.size() << endl; for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].size(); j++) { cout << result[i][j] << " "; } cout << endl; } return 0; } ``` 该实现中的`queens`数组记录了每行所放置的皇后所在列的位置,`result`数组用于存储所有的解。在`n_queens`函数中,首先判断当前行是否已经放置完毕,如果已经放置完毕,则将当前解存储到`result`数组中,然后返回上一层。如果当前行还没有放置完毕,那么就在当前行的所有列中依次尝试放置皇后,如果放置皇后后不会与之前的皇后冲突,则继续递归到下一行。如果当前行所有列都无法放置皇后,则返回上一层。 该实现的时间复杂度为O(n!),空间复杂度为O(n)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值