前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >AcWing 166. 数独(dfs,位运算 剪枝集萃)

AcWing 166. 数独(dfs,位运算 剪枝集萃)

作者头像
glm233
发布2021-04-29 15:33:37
3470
发布2021-04-29 15:33:37
举报
文章被收录于专栏:glm的全栈学习之路
代码语言:javascript
复制
#include<bits/stdc++.h>
using namespace std;
const int N=100,M=9;
char s[N];
int ma[1<<M],ones[1<<M];
int col[M],row[M],cell[3][3];
int lb(int x){
    return x& -x;
}
void init(){
    for(int i=0;i<M;i++){
        col[i]=row[i]=(1<<M)-1;
    }
    for(int i=0;i<3;i++){
        for(int j=0;j<3;j++){
            cell[i][j]=(1<<M)-1;
        }
    }
}
int get(int x,int y){
    return row[x]&col[y]&cell[x/3][y/3];
}
void draw(int x,int y,int t,int flag){
    if(flag)s[x*M+y]=t+'1';
    else s[x*M+y]='.';
    
    int v=1<<t;
    if(!flag)v=-v;
    row[x]-=v;
    col[y]-=v;
    cell[x/3][y/3]-=v;
    
}
bool dfs(int cnt){
    if(!cnt)return 1;
    int minv=10,x,y;
    for(int i=0;i<M;i++){
        for(int j=0;j<M;j++){
            if(s[i*M+j]=='.'){
                int tep=get(i,j);
                if(ones[tep]<minv){
                    x=i,y=j;
                    minv=ones[tep];
                }
            }
        }
    }
    int state=get(x,y);
    for(int i=state;i;i-=lb(i)){
        int tep=ma[lb(i)];
        draw(x,y,tep,1);
        if(dfs(cnt-1))return 1;
        draw(x,y,tep,0);
        
    }
    return 0;
}
int main(){
    for(int i=0;i<M;i++)ma[1<<i]=i;
    for(int i=0;i<1<<M;i++){
        for(int j=0;j<M;j++){
            ones[i]+=i>>j&1;
        }
    }
    while(cin>>s,s[0]!='e'){
        init();
        int cnt=0;
        for(int i=0,k=0;i<M;i++){
            for(int j=0;j<M;j++,k++){
                if(s[k]!='.'){
                    int num=s[k]-'1';
                    draw(i,j,num,1);
                }
                else cnt++;
                
            }
        }
        dfs(cnt);
        cout<<s<<endl;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/04/27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档