解数独(sudouku)

2016-01-07  本文已影响128人  极速魔法

C++实现

#include<iostream>//数独问题的求解,回溯算法
#include<algorithm>
using namespace std;
int map[9][9];

bool isplace(int count)//判断行、列、宫是否有重复的数
{
    int row=count/9;
    int col=count%9;
    int j;
    //同一行
    for(j=0;j<9;j++)
    {
        if(map[row][j]==map[row][col]&& j!=col)
        {
                return false;
        }
    }
    //同一列
    for(j=0;j<9;j++)
    {
        if(map[j][col]==map[row][col] && j!=row)
                return false;
    }
    //同一个宫
    int temprow=row/3*3;
    int tempcol=col/3*3;
    for(j=temprow;j<temprow+3;j++)
    {
        for(int k=tempcol;k<tempcol+3;k++)
        {
            if(map[j][k]==map[row][col] && j!=row && k!=col)
            {
                return false;
            }
        }
    }
   return true;
}

void backtrace(int count)
{
    if(count==81)
    {
        cout<<"result"<<endl;
        for(int i=0;i<9;i++)
        {
            for(int j=0;j<9;j++)
            {
                cout<<map[i][j]<<" ";
            }
             cout<<endl;
        }
    }

    int row=count/9;
    int col=count%9;
    if(map[row][col]==0)
    {
        for(int i=1;i<=9;i++)
        {
            map[row][col]=i;//赋值
            if(isplace(count))
            {
                backtrace(count+1);//放下一个
            }
        }
        map[row][col]=0;//回溯
    }
    else
    {
        backtrace(count+1);//不是空格,下一个数
    }
}

int main()
{
    for(int i=0;i<9;i++)
    {
        for(int j=0;j<9;j++)
        {
             cin>>map[i][j];
        }
    }
    backtrace(0);
    return 0;
}

实例

“芬兰数学家因卡拉花费3个月设计出了世界上迄今难度最大的数独游戏,而且它只有一个答案。因卡拉说只有思考能力最快、头脑最聪明的人才能破解这个游戏。”

数独题目

运行程序输入,空格用0表示:

8 0 0 0 0 0 0 0 0
0 0 3 6 0 0 0 0 0
0 7 0 0 9 0 2 0 0
0 5 0 0 0 7 0 0 0
0 0 0 0 4 5 7 0 0
0 0 0 1 0 0 0 3 0
0 0 1 0 0 0 0 6 8
0 0 8 5 0 0 0 1 0
0 9 0 0 0 0 4 0 0

运行结果

result
8 1 2 7 5 3 6 4 9
9 4 3 6 8 2 1 7 5
6 7 5 4 9 1 2 8 3
1 5 4 2 3 7 8 9 6
3 6 9 8 4 5 7 2 1
2 8 7 1 6 9 5 3 4
5 2 1 9 7 4 3 6 8
4 3 8 5 2 6 9 1 7
7 9 6 3 1 8 4 5 2

上一篇 下一篇

猜你喜欢

热点阅读