1 #include "stdafx.h"
2 #include <iostream>
3
4 using namespace std;
5
6 /* 构造完成标志 */
7 bool sign = false;
8
9 /* 创建数独矩阵 */
10 int num[9][9];
11
12 /* 函数声明 */
13 void Input();
14 void Output();
15 bool Check(int n, int key);
16 int DFS(int n);
17
18 /* 主函数 */
19 int main()
20 {
21 cout << "请输入一个9*9的数独矩阵,空位以0表示:" << endl;
22 Input();
23 DFS(0);
24 Output();
25 system("pause");
26 }
27
28 /* 读入数独矩阵 */
29 void Input()
30 {
31 char temp[9][9];
32 for (int i = 0; i < 9; i++)
33 {
34 for (int j = 0; j < 9; j++)
35 {
36 cin >> temp[i][j];
37 num[i][j] = temp[i][j] - '0';
38 }
39 }
40 }
41
42 /* 输出数独矩阵 */
43 void Output()
44 {
45 cout << endl;
46 for (int i = 0; i < 9; i++)
47 {
48 for (int j = 0; j < 9; j++)
49 {
50 cout << num[i][j] << " ";
51 if (j % 3 == 2)
52 {
53 cout << " ";
54 }
55 }
56 cout << endl;
57 if (i % 3 == 2)
58 {
59 cout << endl;
60 }
61 }
62 }
63
64 /* 判断key填入n时是否满足条件 */
65 bool Check(int n, int key)
66 {
67 /* 判断n所在横列是否合法 */
68 for (int i = 0; i < 9; i++)
69 {
70 /* j为n竖坐标 */
71 int j = n / 9;
72 if (num[j][i] == key) return false;
73 }
74
75 /* 判断n所在竖列是否合法 */
76 for (int i = 0; i < 9; i++)
77 {
78 /* j为n横坐标 */
79 int j = n % 9;
80 if (num[i][j] == key) return false;
81 }
82
83 /* x为n所在的小九宫格左顶点竖坐标 */
84 int x = n / 9 / 3 * 3;
85
86 /* y为n所在的小九宫格左顶点横坐标 */
87 int y = n % 9 / 3 * 3;
88
89 /* 判断n所在的小九宫格是否合法 */
90 for (int i = x; i < x + 3; i++)
91 {
92 for (int j = y; j < y + 3; j++)
93 {
94 if (num[i][j] == key) return false;
95 }
96 }
97
98 /* 全部合法,返回正确 */
99 return true;
100 }
101
102 /* 深搜构造数独 */
103 int DFS(int n)
104 {
105 /* 所有的都符合,退出递归 */
106 if (n > 80)
107 {
108 sign = true;
109 return 0;
110 }
111 /* 当前位不为空时跳过 */
112 if (num[n/9][n%9] != 0)
113 {
114 DFS(n+1);
115 }
116 else
117 {
118 /* 否则对当前位进行枚举测试 */
119 for (int i = 1; i <= 9; i++)
120 {
121 /* 满足条件时填入数字 */
122 if (Check(n, i) == true)
123 {
124 num[n/9][n%9] = i;
125 /* 继续搜索 */
126 DFS(n+1);
127 /* 返回时如果构造成功,则直接退出 */
128 if (sign == true) return 0;
129 /* 如果构造不成功,还原当前位 */
130 num[n/9][n%9] = 0;
131 }
132 }
133 } }