P1219 [USACO1.5]八皇后 Checker Challenge

吐槽

经典的八皇后问题,使用DFS的方法。

看到好多解析上讲回溯,剪枝啊什么的。感觉好难,其实就是DFS+剪枝=回溯(可能是我菜,不了解)

回溯就是,使劲往里面钻,一遍钻一遍判断我当前的状态行不行(符合不符合条件),不符合呢,就换个地方钻。符合就一直钻下去,钻到底就成功了。

 

 

#include<bits/stdc++.h>
using namespace std;
int tot=0;
int n;
int col[13];
int cnt;
bool check(int c,int r)//判断在位置r是否满足答案
{
    for(int i=0;i<r;i++){
        if(col[i]==c||(abs(col[i]-c)==abs(i-r))){
            return false;
        }
    }
    return true;
}
void dfs(int r)//r代表行,c代表列
{
    if(r==n){
        if(cnt<3){
            for(int i=0;i<n;i++){
                cout<<col[i]+1<<" ";
            }
            cout<<endl;
            cnt++;
        }
        tot++;
        return;
    }
    for(int c=0;c<n;c++){
        if(check(c,r)){
            col[r]=c;
            dfs(r+1);
        }
    }
}
int main()
{
    cnt=0;
    cin>>n;
    dfs(0);
    cout<<tot;
    return 0;

}

 

posted @ 2021-04-07 15:26  南理工学渣  阅读(60)  评论(0)    收藏  举报