数独游戏

本文分享了一个使用深度优先搜索(DFS)算法编写的数独计算器,通过递归填充空格,检查每一步的合法性,直至找到解决方案或确认无解。读者可以了解如何利用DFS解决经典的数独问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

闲来无事,用dfs写个数独计算器

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>

using namespace std;

int n = 9, m = 9;
string s[10000]
bool check(int x, int y) {
    bool book[20];
    memset(book, 0, sizeof(book));
    for (int i = x / 3 * 3; i <= x / 3 * 3 + 2; i++)
        for (int j = y / 3 * 3; j <= y / 3 * 3 + 2; j++)
            if (s[i][j] != '*')
                if (book[s[i][j] - '0'] == 0)
                    book[s[i][j] - '0'] = 1;
                else
                    return false;
    memset(book, 0, sizeof(book));
    for (int i = 0; i < n; i++)
        if (s[i][y] != '*')
            if (book[s[i][y] - '0'] == 0)
                book[s[i][y] - '0'] = 1;
            else
                return false;
    memset(book, 0, sizeof(book));
    for (int i = 0; i < m; i++)
        if (s[x][i] != '*')
            if (book[s[x][i] - '0'] == 0)
                book[s[x][i] - '0'] = 1;
            else
                return false;
    return true;
}

bool judge() {
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (s[i][j] == '*') return false;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (!check(i, j)) return false;
    return true;
}

void dfs() {
    if (judge()) {
        printf("-----------\n");
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                printf("%c", s[i][j]);
                if ((j + 1) % 3 == 0) printf(" ");
            }
            printf("\n");
            if ((i + 1) % 3 == 0) printf("\n");
        }
        exit(0);
    }
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (s[i][j] == '*') {
                for (int l = 1; l <= 9; l++) {
                    s[i][j] = l + '0';
                    if (check(i, j)) dfs();
                    s[i][j] = '*';
                }
                return;
            }
    return;
}

int main(int argc, char const *argv[]) {
    printf("请输入9×9的数独矩阵(需要填数的格子请填*):\n");
    for (int i = 0; i < n; i++) cin >> s[i];
    dfs();
    printf("无解\n");
    return 0;
}

代码演示

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值