數獨解法c++實現


轉自http://blog.csdn.net/qq_31558353/article/details/50615760

用個小樣列(據說是世界上最難的數獨,10s過)

//<pre code_snippet_id="1592833" snippet_file_name="blog_20160301_1_4048211" name="code" class="cpp">#include <iostream>
#include<iostream> 
using namespace std;
 
/* 構造完成標志 */
bool sign = false;
 
/* 創建數獨矩陣 */
int num[9][9];
 
/* 函數聲明 */
void Input();
void Output();
bool Check(int n, int key);
int DFS(int n);
 
/* 主函數 */
int main()
{
    cout << "請輸入一個9*9的數獨矩陣,空位以0表示:" << endl;
    Input();
    DFS(0);
    Output();
    system("pause");
}
 
/* 讀入數獨矩陣 */
void Input()
{
    char temp[9][9];
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            cin >> temp[i][j];
            num[i][j] = temp[i][j] - '0';
        }
    }
}
 
/* 輸出數獨矩陣 */
void Output()
{
    cout << endl;
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 9; j++)
        {
            cout << num[i][j] << " ";
            if (j % 3 == 2)
            {
                cout << "   ";
            }
        }
        cout << endl;
        if (i % 3 == 2)
        {
            cout << endl;
        }
    }
}
 
/* 判斷key填入n時是否滿足條件 */
bool Check(int n, int key)
{
    /* 判斷n所在橫列是否合法 */
    for (int i = 0; i < 9; i++)
    {
        /* j為n豎坐標 */
        int j = n / 9;
        if (num[j][i] == key) return false;
    }
 
    /* 判斷n所在豎列是否合法 */
    for (int i = 0; i < 9; i++)
    {
        /* j為n橫坐標 */
        int j = n % 9;
        if (num[i][j] == key) return false;
    }
 
    /* x為n所在的小九宮格左頂點豎坐標 */
    int x = n / 9 / 3 * 3;
 
    /* y為n所在的小九宮格左頂點橫坐標 */
    int y = n % 9 / 3 * 3;
 
    /* 判斷n所在的小九宮格是否合法 */
    for (int i = x; i < x + 3; i++)
    {
        for (int j = y; j < y + 3; j++)
        {
            if (num[i][j] == key) return false;
        }
    }
 
    /* 全部合法,返回正確 */
    return true;
}
 
/* 深搜構造數獨 */
int DFS(int n)
{
    /* 所有的都符合,退出遞歸 */
    if (n > 80)
    {
        sign = true;
        return 0;
    }
    /* 當前位不為空時跳過 */
    if (num[n/9][n%9] != 0)
    {
        DFS(n+1);
    }
    else
    {
        /* 否則對當前位進行枚舉測試 */
        for (int i = 1; i <= 9; i++)
        {
            /* 滿足條件時填入數字 */
            if (Check(n, i) == true)
            {
                num[n/9][n%9] = i;
                /* 繼續搜索 */
                DFS(n+1);
                /* 返回時如果構造成功,則直接退出 */
                if (sign == true) return 0;
                /* 如果構造不成功,還原當前位 */
                num[n/9][n%9] = 0;
            }
        }
    }
}

輸入

感受一下輸出

計算機是個偉大的發明

百度百科上的世界最難數獨秒過,垃圾~~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM