数独

· · 个人记录

朴素dfs

想要解决数独问题,我们不难想到可以在每个位置逐个 枚举所有数字,可以使用 dfs 算法。不过该算法并非本文主题,故仅附一份暴力代码供参考。

#include <iostream>
#include <cstring>
using namespace std;

int a[15][15];
bool r[15][15], c[15][15], g[15][15];

void print()
{
    for (int i = 1; i <= 9; ++i)
    {
        for (int j = 1; j <= 9; ++j)
            cout << a[i][j] << ' ';
        cout << '\n';
    }
}

bool chk()
{
    memset(r, false, sizeof r);
    memset(c, false, sizeof c);
    memset(g, false, sizeof g);
    for (int i = 1; i <= 9; ++i)
        for (int j = 1; j <= 9; ++j)
        {
            int x = a[i][j];
            if (r[i][x] || c[j][x] || g[(i-1)/3*3+(j-1)/3+1][x]) return false;
            r[i][x] = c[j][x] = g[(i-1)/3*3+(j-1)/3+1][x] = true;
        }
    return true;
}

void dfs(int x, int y)
{
    if (a[x][y])
    {
        if (x == 9 && y == 9)
        {
            if (chk())
            {
                print();
                exit(0);
            }
        }
        else if (y == 9) dfs(x+1, 1);
        else dfs(x, y+1);
        return;
    }
    for (int i = 1; i <= 9; ++i)
    {
        a[x][y] = i;
        if (x == 9 && y == 9)
        {
            if (chk())
            {
                print();
                exit(0);
            }
        }
        else if (y == 9) dfs(x+1, 1);
        else dfs(x, y+1);
        a[x][y] = 0;
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    for (int i = 1; i <= 9; ++i)
        for (int j = 1; j <= 9; ++j)
            cin >> a[i][j];
    dfs(1, 1);
    return 0;
}

有心的读者可以发现该方法时间复杂度极高,所以必然不可行,那么如何优化呢?

剪枝

剪枝是一种常见的搜索优化方式

熟悉 dfs 的读者应知道其搜索过程可呈现为一棵树,我们称之为 dfs 树,过程中每个选择都会对应其中的一个子树。
然而对一些选择后对最后结果一定没有任何价值的选项,我们自然而然地可以排除他们。具体地,我们应去除其对应子树,避免浪费我们的时间。

不过这样说还是有些抽象,那接下来让我们看看剪枝的具体实现方式。

1.可行性剪枝

可行性剪枝是最直观、基础的剪枝方式,具体来说就是去除掉不符合规则的选项。
在数独这个问题中,其具体表现如下:

8 0 0 0 0 0 0 0 0
0 0 3 6 0 0 0 0 0
0 7 0 0 9 0 2 0 0
0 5 0 0 0 7 0 0 0
0 0 0 0 4 5 7 0 0
0 0 0 1 0 0 0 3 0
0 0 1 0 0 0 0 6 8
0 0 8 5 0 0 0 1 0
0 9 0 0 0 0 4 0 0

在该数独中,如果我们在 (1, 2) 的位置填入数字 8 ,显然违反规则,所以该选项不用考虑。然而在上文所给代码中,该选项被试验了一遍,大大降低了效率,如果我们使用剪枝便可加快速度。

具体地,可以添加如下代码优化:

for (int i = 1; i <= 9; ++i)
{
   if (r[x][i] || c[y][i] || g[id[x][y]][i]) continue;
}

其中 r,c,g,id 分别为行、列、宫已选择数字和该位置对应宫号

2.最优性剪枝

最优性剪枝也是一种较好理解的方式,具体为如果题目要求解最大、最小值等类型时,一旦目前所得数值大于已经求出的最优解,且后续数值离最优越来越远时,就可以停止搜索。
不过在数独问题中,我们无须利用此方法,故不做深入讲解。

3.重复性剪枝

这类剪枝的想法在于,如果你搜索到某一部分,发现这与之前已经计算过的某个方案完全等效,那我们就可以停止枚举,直接调用之前的结果。
不过这类剪枝在数独问题中也没有太大应用。

4.搜索顺序剪枝

这种方式就相对较抽象,利用了贪心思想。具体来说,我们如果有两个价值相等的部分,但其所需的尝试数量不同,我们应先解决次数较少的一个,因为其性价比更高。

不过这种方法在数独问题中其实更好理解,就是选择先枚举可填充数字最少的格子。作为高等智慧生命的我们,生活中自然也是利用这种高效的方式,那计算机自然也可以实现类似功能。

实现

讲解了理论部分,下面就是实现部分。作者的代码主要运用了 可行性剪枝 和 搜索顺序剪枝。

不过由于想要找到目前可填数字最少的格子,暴力枚举是 O( 9^3 ) 的,大大减慢了我们的速度。我们需用到 位运算 进行优化,优化过程不过多赘述,相信读者看代码可以理解。

#include <iostream>
#define lowbit(x) (x & -x)
using namespace std;

const int N = (1 << 9);
int n, a[10][10], cnt[N], f[N], r[10], c[10], g[10], cntn;
char ch;
int id[10][10] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                  {0, 1, 1, 1, 2, 2, 2, 3, 3, 3},
                  {0, 1, 1, 1, 2, 2, 2, 3, 3, 3},
                  {0, 1, 1, 1, 2, 2, 2, 3, 3, 3},
                  {0, 4, 4, 4, 5, 5, 5, 6, 6, 6},
                  {0, 4, 4, 4, 5, 5, 5, 6, 6, 6},
                  {0, 4, 4, 4, 5, 5, 5, 6, 6, 6},
                  {0, 7, 7, 7, 8, 8, 8, 9, 9, 9},
                  {0, 7, 7, 7, 8, 8, 8, 9, 9, 9},
                  {0, 7, 7, 7, 8, 8, 8, 9, 9, 9}};

int get(int x)
{
    int cnt = 0;
    while (x)
    {
        ++cnt;
        x -= lowbit(x);
    }
    return cnt;
}

void qc(int x, int y, int num)
{
    r[x] ^= (1 << num);
    c[y] ^= (1 << num);
    g[id[x][y]] ^= (1 << num);
}

bool dfs(int cntn)
{
    if (!cntn) return true;
    int mn = 10, x, y, num;
    for (int i = 1; i <= 9; ++i)
        for (int j = 1; j <= 9; ++j)
            if (!a[i][j])
            {
                num = r[i] & c[j] & g[id[i][j]];
                if (cnt[num] < mn)
                {
                    x = i, y = j;
                    mn = cnt[num];
                }
            }
    num = r[x] & c[y] & g[id[x][y]];
    while (num)
    {
        int nw = f[lowbit(num)];
        a[x][y] = nw + 1;
        qc(x, y, nw);
        if (dfs(cntn - 1)) return true;
        a[x][y] = 0;
        qc(x, y, nw);
        num -= lowbit(num);
    }
    return false;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    for (int i = 0; i < N; ++i) cnt[i] = get(i);
    for (int i = 0; i <= 8; ++i) f[1<<i] = i;
    while (true)
    {
        cntn = 0;
        for (int i = 1; i <= 9; ++i) r[i] = c[i] = g[i] = N - 1;
        for (int i = 1; i <= 9; ++i)
            for (int j = 1; j <= 9; ++j)
            {
                cin >> ch;
                if (ch == 'e') return 0;
                if (ch == '.')
                {
                    a[i][j] = 0;
                    ++cntn;
                }
                else
                {
                    a[i][j] = ch - '0';
                    qc(i, j, a[i][j]-1);
                }
            }
        if (dfs(cntn))
            for (int i = 1; i <= 9; ++i)
                for (int j = 1; j <= 9; ++j)
                    cout << a[i][j];
        cout << '\n';
    }
    return 0;
}