HDU - 1426 九宫格+输入处理

版权声明:博主的博客不值钱随便转载但要注明出处 https://blog.csdn.net/easylovecsdn/article/details/83153290

除了输入有点坑别的都还好

#include <bits/stdc++.h>

using namespace std;

#define     max(x, y)      x >= y ? x : y
#define     min(x, y)      x <= y ? x : y

#define     INF     0x3f3f3f3f

typedef struct node
{
    int x;
    int y;
    node(int xx, int yy)
    {
        x = xx;
        y = yy;
    }
} node;



char m[10][10];
int M[10][10];
vector<node> p;
int flag;
int cnt;

bool judge(int x, int y, int v)
{
    for (int i = 0; i < 9; i++) {              //检查行列
        if (M[i][y] == v) return false;
        if (M[x][i] == v) return false;
    }

    int xx = (x / 3) * 3;
    int yy = (y / 3) * 3;

    for (int i = xx; i < xx + 3; i++) {        //检查3*3
        for (int j = yy; j < yy + 3; j++) {
            if (M[i][j] == v) return false;
        }
    }

    return true;
}

void print()
{
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            if (j) cout << " ";
            cout << M[i][j];
        }
        cout << endl;
    }
}


void dfs(int index)
{

    if (flag) return ;

    if (index == p.size()) {
        flag = 1;
        print();
        return ;
    }


    int x = p[index].x;
    int y = p[index].y;

    for (int i = 1; i <= 9; i++) {

        if (judge(x, y, i)) {

            M[x][y] = i;
            dfs(index + 1);
        }

        if (flag) return ;
    }

    M[x][y] = 0;

}

void init()
{
    p.clear();
    flag = 0;
}

char s[105];

int main()
{

    cnt = 0;

    while (~scanf("%s", s))
    {
        init();

        M[0][0] = s[0] == '?' ? 0 : (s[0] - '0');

        if (M[0][0] == 0) p.push_back(node(0, 0));

        for (int i = 1; i < 9; i++) {
            scanf("%s", s);
            M[0][i] = s[0] == '?' ? 0 : (s[0] - '0');

            if (M[0][i] == 0) p.push_back(node(0, i));
        }


        for (int i = 1; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                scanf("%s", s);
                M[i][j] = s[0] == '?' ? 0 : (s[0] - '0');

                if (M[i][j] == 0) p.push_back(node(i, j));
            }
        }



        if (cnt++) cout << endl;


        dfs(0);


    }


    return 0;
}

附加:你敢不敢试一下这组数据

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

猜你喜欢

转载自blog.csdn.net/easylovecsdn/article/details/83153290