题解 | #八皇后#非DFS解法

八皇后

https://www.nowcoder.com/practice/fbf428ecb0574236a2a0295e1fa854cb

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

vector<string> ans;
bool isGood(string str) {
    for (int i = 0; i < 8; i++) {
        for (int j = i + 1; j < 8; j++) {
            if (abs(str[i] - str[j]) == abs(i - j)) {
                return false;
            }
        }
    }
    return true;
}
void select(int loop, string str, string cur) {
    if (loop == 9 && isGood(cur)) {
        ans.push_back(cur);
        return;
    }
    for (int i = 0; i < str.size(); i++) {
        string temp = str.substr(i, 1);
        string cp = str;
        cp.erase(i, 1);
        select(loop + 1, cp, cur + temp);
    }
    return;
}

int main() {
    int x;
    string base = "12345678";
    ans.reserve(92);
    while (cin >> x) { // 注意 while 处理多个 case
        // for(int i=0;i<8;i++){
        select(1, base, "");//枚举串base的所有排列方式,若为解,则存入vector
        sort(ans.begin(), ans.end());
        cout << ans[x - 1] << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务