《ybtoj高效进阶》第一部分第四章例题2 数独游戏

题目大意

P1784数独的多组数据版,文件末尾end

思路

P1784数独一样,但是需要注意,我们的输入是字符串形式,而且多组数据,需要初始化和输入变数字
code:

#include <cstdio>
#include <queue>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int a[10], b[10], c[10], d[10] = {
    
     1, 2, 4, 8, 16, 32, 64, 128, 256, 0 };
int f[9][9], s, op[512], r[512], o2o;
bool o;
string x;
void dfs(int xx) {
    
    
    if (o == 1)
        return;
    if (xx == s) {
    
    
        o = 1;
        return;
    }
    int x, y, z = 10;
    for (int i = 0; i < 9; i++)
        for (int j = 0; j < 9; j++) {
    
    
            if (f[i][j] == -1 && op[a[i] & b[j] & c[i / 3 * 3 + j / 3]] <= z) {
    
    
                z = op[a[i] & b[j] & c[i / 3 * 3 + j / 3]];
                if (z == 0) {
    
    
                    return;
                }
                x = i, y = j;
            }
        }
    for (int k = a[x] & b[y] & c[x / 3 * 3 + y / 3]; k; k -= k & -k) {
    
    
        f[x][y] = r[k & -k];
        a[x] ^= d[f[x][y]], b[y] ^= d[f[x][y]], c[x / 3 * 3 + y / 3] ^= d[f[x][y]];
        dfs(xx + 1);
        if (o == 1)
            return;
        a[x] ^= d[f[x][y]], b[y] ^= d[f[x][y]], c[x / 3 * 3 + y / 3] ^= d[f[x][y]];
    }
    f[x][y] = -1;
    return;
}
int main() {
    
    
    cin >> x;
    for (int i = 0; i < 9; i++) r[d[i]] = i;
    for (int i = 0; i < 512; i++) {
    
    
        int i2 = i;
        for (; i2; i2 -= i2 & -i2) op[i]++;
    }
    while (x != "end") {
    
    
        memset(f, -1, sizeof(f));
        s = 0;
        o = 0;
        for (int i = 0; i < 9; i++) a[i] = b[i] = c[i] = 511;
        for (int i = 0; i < 9; i++)
            for (int j = 0; j < 9; j++)
                if (x[i * 9 + j] != '.')
                    f[i][j] = x[i * 9 + j] - '1', a[i] ^= d[f[i][j]], b[j] ^= d[f[i][j]],
                    c[i / 3 * 3 + j / 3] ^= d[f[i][j]];
                else
                    s++;
        dfs(0);
        for (int i = 0; i < 9; i++)
            for (int j = 0; j < 9; j++) cout << f[i][j] + 1;
        cout << endl;
        cin >> x;
    }
    return 0;
}
//哇神奇OJ帮我改了码风???

猜你喜欢

转载自blog.csdn.net/weixin_49843717/article/details/112989147