数独游戏的C代码实现

人工智能实验时写的代码:

1 //shudu.cpp 数独游戏
2  #include<iostream>
3 #include<iomanip>
4 #include<fstream>
5 #include<cstdlib>//c语言中为#include<stdlib.h>
6 usingnamespace std;
7
8 //定义数据结构
9 int shudu[9][9]={0};
10
11 //初始化数据
12 void init()
13 {
14 int i=0,j=0;
15 ifstream fin("input.txt");//打开文件
16 //读入数字
17 for(i=0;i<9;i++)
18 for(j=0;j<9;j++)
19 fin>>shudu[i][j];
20 fin.close();
21 //输出刚刚读入的数据
22 cout<<"The init structure is:"<<endl;
23 for(i=0;i<9;i++,cout<<endl)
24 for(j=0;j<9;j++)
25 cout<<shudu[i][j]<<'';
26 }
27
28 //检查在(x,y)位置处赋予i值是否满足行列互不相同的条件
29 bool checkAssign1(int x,int y,int i)
30 {
31 for(int c=0;c<9;c++) //c是指列
32 if(c!=y && shudu[x][c]==i)
33 returnfalse;
34 for(int r=0;r<9;r++)// r是指行
35 if(r!=x && shudu[r][y]==i)
36 returnfalse;
37 returntrue;
38 }
39
40 //检查(x,y)位置处是否满足其所在大方格中各数互不相同的条件
41 bool checkAssign2(int x,int y,int i)
42 {
43 for(int r=(x/3)*3;r<(x/3)*3+3;r++) // (x/3,y/3)是(x,y)所在的大方格的位置
44 for(int c=(y/3)*3;c<(y/3*3)+3;c++) // x/3*3和y/3*3分别是(x,y)所在大方格
45 //位置的起始位置
46 {
47 if(shudu[r][c]==i)
48 if(r==x && c==y)
49 continue;
50 else
51 returnfalse;
52 }
53 returntrue;
54 }
55
56 //81个点中分别给每一个点搜索可行解
57 bool search(int depth)
58 {
59 if(depth>=81)
60 {
61 returntrue;
62 }
63 int x,y;//检查当前位置(x,y)有没被赋值,没有则尝试赋值
64 //检查是否违法约束条件
65 x=depth/9;y=depth%9;
66 if(shudu[x][y]!=0)//(x,y)已赋值
67 return search(depth+1);
68 else
69 for(int i=1;i<=9;i++)
70 {
71 shudu[x][y]=i;
72 if(checkAssign1(x,y,i) && checkAssign2(x,y,i))
73 {
74 if(search(depth+1))
75 returntrue;
76 }
77 shudu[x][y]=0;
78 }
79 returnfalse;
80 }
81
82
83 int main()
84 {
85 cout<<" 数独游戏设计 "<<endl;
86 cout<<" 刘懿设计 "<<endl;
87 cout<<"--------------------------"<<endl;
88 //define the data structure and input the data
89 init();
90 cout<<"--------------------------"<<endl;
91 if(search(0)) //search();
92 {//output the answer
93 cout<<"The answer is:"<<endl;
94 for(int i=0;i<9;i++,cout<<endl)
95 for(int j=0;j<9;j++)
96 cout<<shudu[i][j]<<'';
97 }
98 else
99 {
100 cout<<"haven't found a resolution"<<endl;
101 }
102 system("pause"); //让画面停留,避免一闪而过
103 return0;
104 }
posted @ 2011-02-27 15:43  busyfruit  阅读(7804)  评论(0编辑  收藏  举报