数独游戏的C代码实现

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

1 // shudu.cpp 数独游戏
2   #include < iostream >
3 #include < iomanip >
4 #include < fstream >
5 #include < cstdlib > // c语言中为#include<stdlib.h>
6 using namespace 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 return false ;
34 for ( int r = 0 ;r < 9 ;r ++ ) // r是指行
35 if (r != x && shudu[r][y] == i)
36 return false ;
37 return true ;
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 return false ;
52 }
53 return true ;
54 }
55
56 // 81个点中分别给每一个点搜索可行解
57 bool search( int depth)
58 {
59 if (depth >= 81 )
60 {
61 return true ;
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 return true ;
76 }
77 shudu[x][y] = 0 ;
78 }
79 return false ;
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 return 0 ;
104 }

转载于:https://www.cnblogs.com/lyfruit/archive/2011/02/27/1966312.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值