题解 | #八皇后#

八皇后

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

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<string>res;
int Q[8][8]={0};
bool isValid(int row,int col){
    int i,j;
    for(i=0;i<8;i++){
        if(Q[i][col])return false;
    }
    for(i=row,j=col;i>=0&&j>=0;i--,j--){
        if(Q[i][j])return false;
    }
    for(i=row,j=col;i>=0&&j<8;i--,j++){
        if(Q[i][j])return false;
    }
    return true;
}
void backtracking(int row,string temp){
    if(temp.length()==8){
        res.push_back(temp);
        return;
    }
    for(int i=0;i<8;i++){
        if(isValid(row, i)){
            Q[row][i]=1;
            char c=i+1+'0';
            temp.push_back(c);
            backtracking(row+1,temp);
            Q[row][i]=0;
            temp.pop_back();//这一步很重要(回退)
        }
    }
}
int main() {
    int  b;
    string temp="";
    backtracking(0, temp);
    sort(res.begin(),res.end());
    while (cin  >> b) { // 注意 while 处理多个 case
        cout << res[b-1] << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 15:19
简历上能写3个月吗?
码农索隆:大胆写,主要你能把实习经历包装好,可以看一下我这篇帖子https://www.nowcoder.com/share/jump/4888395581180798063
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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