数独(dfs+剪枝)

博客围绕数独问题展开,题目是在九宫格中填数,使横行、纵行和每一块都包含1 - 9。解题思路采用深搜,用col和row记录横行、纵行未用的数,cell标记未用的数,通过剪枝找到某个数可填的最小可能,还给出了代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:数独

参考:yxc
题意:就是给你一个九宫格,让你填数,使横行包含1 ~ 9,纵行包含1 ~ 9,每一块包含1 ~ 9 。
思路:本题采用深搜,然后通过用col和row分别记录横行和纵行没有被用过的数,cell来标记没有被用过的数,通过0代表这个数已经被用过了,1代表这个数没有被用过,然后通过剪枝找到某个数可以填数的最小可能,这个最小可能通过row[x] & cell[x/3][y/3] & col[y]来找到。
代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100;
const int N = 9;
char str[maxn];
int cell[10][10],row[maxn],col[maxn];
int mp[1<<N], ones[1<<N];
int lowbit(int x)
{
    return x&(-x);
}
void set_init()
{
    for(int i = 0; i < N; i++ )mp[1<<i] = i;
    for(int i = 0; i < 1<<N; i++)
    {
        int cn = 0;
        for(int j = i; j; j -= lowbit(j))cn++;
        ones[i] = cn;
    }
}
void init()
{
    for(int i = 0; i < N; i++)row[i] = (1<<N)-1, col[i] = (1<<N)-1;
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            cell[i][j] = (1<<N)-1;
}
int judge(int x, int y)
{
    return row[x] & cell[x/3][y/3] & col[y];
}
bool dfs(int cnt)
{
    if(!cnt)return true;
    int minn = 10, x, y;
    for(int i = 0; i < N; i++)//找到最小的能填数的位置
    {
        for(int j = 0; j < N; j++)
        {
            if(str[i*N+j] == '.')
            {
                int t = ones[judge(i, j)];
                if(minn > t)minn = t, x = i, y = j;
            }
        }
    }
    for(int i = judge(x, y); i; i -= lowbit(i))
    {
        int t = mp[lowbit(i)];
        row[x] -= 1<<t;
        col[y] -= 1<<t;
        cell[x/3][y/3] -= 1<<t;
        str[x*N+y] = '1'+ t;
        if(dfs(cnt-1))return true;
        row[x] += 1<<t;//恢复现场
        col[y] += 1<< t;
        cell[x/3][y/3] += 1<<t;
        str[x*N+y] = '.';
    }
    return false;
}
int main()
{
    set_init();//预处理
    while(cin>>str && strcmp(str, "end") != 0)
    {
        init();//初始化为全1
        int cnt = 0;
        for(int i = 0, k = 0; i < N; i++)
        {
            for(int j = 0; j < N; j++, k++)
            {
                if(str[k] != '.')
                {
                    int t = str[k] - '1';
                    row[i] -= 1<<t;
                    col[j] -= 1<<t;
                    cell[i/3][j/3] -= 1<<t;
                }
                else cnt++;
            }
        }
        dfs(cnt);
        printf("%s\n", str);
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值