数独问题算法

#include <iostream>

using namespace std;
const int N = 15;
int arr[N][N];
bool answer;

bool check(int row, int col, int val) {
    for (int i = 0; i < 9; i++) {
        if (arr[row][i] == val) {
            return false;
        }
    }
    for (int i = 0; i < 9; i++) {
        if (arr[i][col] == val) {
            return false;
        }
    }

    int lim_row = row / 3 * 3 + 3;
    int lim_col = col / 3 * 3 + 3;
    for (int i = lim_row - 3; i < lim_row; i++) {
        for (int j = lim_col - 3; i < lim_col; j++) {
            if (arr[i][j] == val) {
                return false;
            }
        }
    }
    return true;

}

void dfs(int row, int col) {
    if (col == 9) {
        row++;
        col = 0;
    }
    if (row == 9 && col == 0) {
        answer = true;
        return;
    }
    if (arr[row][col] == 0) {
        for (int i = 1; i <= 9; i++) {
            if (check(row, col, i)) {
                arr[row][col] = i;
                dfs(row, col + 1);
                if (answer) {
                    return;
                }
                arr[row][col] = 0;
            }
        }
    }
    else {
        dfs(row, col + 1);
    }
}

int main() {
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            cin >> arr[i][j];
        }
    }
    dfs(0, 0);
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

/*
0 9 2 4 8 1 7 6 3
4 1 3 7 6 2 9 8 5
8 6 7 3 5 9 4 1 2
6 2 4 1 9 5 3 7 8
7 5 9 8 4 3 1 2 6
1 3 8 6 2 7 5 9 4
2 7 1 5 3 8 6 4 9
3 8 6 9 1 4 2 5 7
0 4 5 2 7 6 8 3 1
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值