数独问题(DFS+回溯)

文章目录

题目

数独游戏的规则是这样的:在一个9x9的方格中,你需要把数字1-9填写到空格当中,并且使方格的每一行和每一列中都包含1-9这九个数字。同时还要保证,空格中用粗线划分成9个3x3的方格也同时包含1-9这九个数字。比如有这样一个题,大家可以仔细观察一下,在这里面每行、每列,以及每个3x3的方格都包含1-9这九个数字。

样例


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

Sample Output
7 1 2 4 6 9 3 5 8
3 6 5 2 8 7 1 9 4
4 9 8 5 1 3 6 7 2
9 2 4 1 5 6 8 3 7
5 7 6 3 9 8 2 4 1
1 8 3 7 2 4 9 6 5
2 3 1 9 7 5 4 8 6
6 4 7 8 3 2 5 1 9
8 5 9 6 4 1 7 2 3

代码

#include<iostream>
#include <cstring>
#include <algorithm>

using namespace std;

struct node {
    int x, y;
};
node arr[105];
char ch;
int Map[10][10];
int N = 0;

bool judge(int num, int x, int y) {
    for (int i = 0; i < 9; ++i) {
        if (Map[i][y] == num || Map[x][i] == num)
            return false;
    }
    x = x / 3 * 3;
    y = y / 3 * 3;
    for (int i = x; i < x + 3; ++i) {
        for (int j = y; j < y + 3; ++j) {
            if (Map[i][j] == num)
                return false;
        }
    }
    return true;
}

void dfs(int dept) {
    if (dept == N) {
        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (j == 8)
                    cout << Map[i][j];
                else
                    cout << Map[i][j] << " ";
            }
            cout << endl;
        }
        return;
    }
    for (int i = 1; i <= 9; ++i) {
        if (judge(i, arr[dept].x, arr[dept].y)) {
            Map[arr[dept].x][arr[dept].y] = i;
            dfs(dept + 1);
            Map[arr[dept].x][arr[dept].y] = 0;
        }
    }
}

int line = 0;

int main() {
    while (cin >> ch) {
        N = 0;
        if (ch == '?') {
            Map[0][0] = 0;
            arr[N].x = 0;
            arr[N].y = 0;
            N++;
        } else
            Map[0][0] = ch - '0';

        for (int i = 0; i < 9; ++i) {
            for (int j = 0; j < 9; ++j) {
                if (i == 0 && j == 0)
                    continue;
                cin >> ch;
                if (ch == '?') {
                    Map[i][j] = 0;
                    arr[N].x = i;
                    arr[N].y = j;
                    N++;
                } else
                    Map[i][j] = ch - '0';
            }
        }

        if (line++)
            cout << endl;
        dfs(0);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值