数独求解
  • 板块学术版
  • 楼主llqqhh
  • 当前回复0
  • 已保存回复0
  • 发布时间2022/11/14 22:27
  • 上次更新2023/10/27 02:55:53
查看原帖
数独求解
525817
llqqhh楼主2022/11/14 22:27

想做一个求解数独的程序

输入时未知数用'?', 字符之间空格隔开

不知道为啥没有输出 求大神帮忙看下

#include <bits/stdc++.h>
using namespace std;
char an[19][19];
int a[10][10];

bool check(int x, int y, int n)
{
    for (int i = 0; i < 9; i++)
    {
        if (a[i][y] == n)
        {
            return 0;
        }
        else if (a[x][i] == n)
        {
            return 0;
        }
    }

    x = x / 3 * 3;
    y = y / 3 * 3;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            if (a[x + i][y + j] == n)
            {
                return 0;
            }
        }
    }
    return 1;
}

void dfs()
{
    int x, y;
    int found = 0;
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            if (a[i][j] == 0)
            {
                x = i;
                y = j;
                found = 1;
            }
        }
    }
    if (!found)
    {
        for (int i = 0; i < 9; i++)
        {
            cout << a[i][0];
            for (int j = 1; j < 9; j++)
            {
                cout << ' ' << a[i][j];
            }
            cout << endl;
        }
        cout << endl;
        return;
    }
    for (int k = 1; k <= 9; k++)
    {
        if (check(x, y, k))
        {
            a[x][y] = k;
            // cout<<a[i][j]<<' '<<i<<' '<<j<<endl;
            dfs();
            a[x][y] = 0;
        }
    }
    //cout << -1;
    return;
}
int main()
{
    for (int i = 0; i < 9; i++)
    {
        cin.getline(an[i], sizeof(an[i]));
    }
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            if (an[i][j * 2] == '?')
            {
                a[i][j] = 0;
            }
            else
            {
                a[i][j] = an[i][j * 2] - '0';
            }
        }
    }
    // for(int i = 0; i < 9; i++)
    // {
    //     for(int j = 0; j < 9; j++)
    //     {
    //         cout << a[i][j];
    //     }
    //     cout << endl;
    // }
    printf("\n");
    dfs();
    //cin.getline(an[0], sizeof(an[0]));
    return 0;
}
2022/11/14 22:27
加载中...