DFS回溯
  • 板块灌水区
  • 楼主McQween2024
  • 当前回复4
  • 已保存回复4
  • 发布时间2025/1/23 10:32
  • 上次更新2025/1/23 10:53:37
查看原帖
DFS回溯
1308575
McQween2024楼主2025/1/23 10:32

05

一、回溯(DFS)

直接上代码:(八皇后(节选))

bool check(int x,int y){
    if(h[x]==0 && l[y]==0 && z[x+y]==0 && f[x-y+n]==0) return 1;
    return 0;
}
void dfs(int x){
    if(x==n+1){
        cnt++;
        if(cnt<=3){
            for(int i=1;i<=n;i++){
                cout<<a[i]<<' ';
            }cout<<endl;
        }
        return ;
    }
    for(int i=1;i<=n;i++){
        if(check(x,i)){
            a[x]=i;
            h[x]++;
            l[i]++;
            z[x+i]++;
            f[x-i+n]++;
            dfs(x+1);
            h[x]--;
            l[i]--;
            z[x+i]--;
            f[x-i+n]--;
        }

    }
}

小学生,自用勿喷

2025/1/23 10:32
加载中...