您的位置:首页 > 其它

数独

2014-03-30 22:44 190 查看
/*****************************************************************
任 务:计算出一个给定的数独。
依 据:已经出现的数字,不可能出现在空的方格中(H、L、G)。
步 骤:排除H、排除L、排除G,确定空方格中的数字。
附   :代码中没有回溯,因为全部为空时,也是一种特殊的数独。
更 新:2014-03-31
*****************************************************************/
#include <iostream>
#include <iomanip>
#include <stdio.h>
#define TEST_H 1
#define TEST_L 1
#define TEST_G 1
#define WAY "/home/wahaha/Zhuo_Mian/456.txt"
using namespace std;
typedef struct sudoku
{
int  show;
bool maybe[11];
}sudoku;
/**************************************
函数名:get_out
功  能:进行(H)、列(L)、宫(G)的排除
**************************************/
void get_out( sudoku (*T)[11],const int H,const int L )
{
#if(TEST_H)
for(int l=1; l<=9; l++)
if( l != L || T[H][l].show != 0)
T[H][L].maybe[ T[H][l].show ] = false;
#endif

#if(TEST_L)
for(int h=1; h<=9; h++)
if( h != H || T[h][L].show != 0 )
T[H][L].maybe[ T[h][L].show ] = false;
#endif

#if(TEST_G)
for(int h=1; h<=3; h++)
for(int l=1; l<=3; l++)
if( (l != L && h != H) || T[H][L].show != 0 )
T[H][L].maybe[ T[H/3*3+h][L/3*3+l].show ] = false;
#endif
}
/**************************************
函数名:write_answer
功  能:确定空方格中的数字(修改中)
**************************************/
void write_answer(sudoku (*T)[11],const int H,const int L)
{
for(int i=1; i<=9; i++)
if( T[H][L].maybe[i] == true)
T[H][L].show = i;
}
/**************************************
函数名:whether_or_not
功  能:判断是否结束数独的计算
**************************************/
bool whether_or_not(sudoku (*T)[11])
{
for(int h=1; h<=9; h++)
for(int l=1; l<=9; l++)
if(T[h][l].show == 0)
return false;
return true;
}
/**************************************
函数名:out_print
功  能:输出数独
**************************************/
void out_print(sudoku (*T)[11])
{
for(int h=1; h<=9; h++)
{
for(int l=1; l<=9; l++)
{
cout<<setw(2)<<T[h][l].show;
if(l % 3 == 0)
cout<<"  ";
}
cout<<endl;
if(h % 3 == 0)
cout<<endl;
}
}
/**************************************
函数名:in_printf
功  能:输入数据,并初始化
**************************************/
void in_printf(sudoku (*T)[11])
{
freopen(WAY,"r",stdin);
for(int h=1; h<=9; h++)
for(int l=1; l<=9; l++)
cin>>T[h][l].show;

for(int h=1; h<=9; h++)
for(int l=1; l<=9; l++)
if( T[h][l].show == 0 )
for(int i=0; i<=10; i++)
T[h][l].maybe[i] = true;
}
/**************************************
函数名:main
功  能:解一个数独
**************************************/
int main(void)
{
sudoku example[11][11];
in_printf(example);
bool find = false;
while( !find )
{
for(int h=1; h<=9; h++)
for(int l=1; l<=9; l++)
if(example[h][l].show == 0)
{
get_out(example,h,l);
write_answer(example,h,l);
}
find = whether_or_not(example);
}
out_print( example );
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数独