题目
你一定听说过“数独”游戏。
如:
玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。
数独的答案都是唯一的,所以,多个解也称为无解。
本图的数字据说是芬兰数学家花了3个月的时间设计出来的较难的题目。但对会使用计算机编程的你来说,恐怕易如反掌了。
本题的要求就是输入数独题目,程序输出数独的唯一解。我们保证所有已知数据的格式都是合法的,并且题目有唯一的解。
格式要求
输入9行,每行9个数字,0代表未知,其它数字为已知。
输出9行,每行9个数字表示数独的解。
样例
输入(即图中题目):
005300000
800000020
070010500
400005300
010070006
003200080
060500009
004000030
000009700
1
2
3
4
5
6
7
8
9
程序应该输出:
145327698
839654127
672918543
496185372
218473956
753296481
367542819
984761235
521839764
1
2
3
4
5
6
7
8
9
再例如,输入:
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400
1
2
3
4
5
6
7
8
9
程序应该输出:
812753649
943682175
675491283
154237896
369845721
287169534
521974368
438526917
796318452
1
2
3
4
5
6
7
8
9
资源约定
峰值内存消耗 < 256M
CPU消耗 < 2000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。
所有代码放在同一个源文件中,调试通过后,拷贝提交该源码。
注意: main函数需要返回0
注意: 只使用ANSI C/ANSI C++ 标准,不要调用依赖于编译环境或操作系统的特殊函数。
注意: 所有依赖的函数必须明确地在源文件中 #include , 不能通过工程设置而省略常用头文件。
提交时,注意选择所期望的编译器类型。
思路:
用比特位表示每一行,每一列,每一个block已经有的值。
然后依次dfs判断每个成员。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int row[9] = {0};
int column[9] = {0};
int block[3][3] = {0};
bool found = false;
void dfs(vector<string> &str, int x, int y) {
if (x == 9) {
for (int i = 0; i < 9; i++) {
cout << str[i] << endl;
}
found = true;
return;
}
if (str[x][y] != '0') {
if (y + 1 < 9) {
dfs(str, x, y + 1);
}
else {
dfs(str, x + 1, 0);
}
return;
}
int check = row[x] | column[y] | block[x/3][y/3];
for (int i = 1; i < 10; i++) {
if (check & (1 << i)) {
continue;
}
else {
row[x] |= (1 << i);
column[y] |= (1 << i);
block[x/3][y/3] |= (1 << i);
str[x][y] = i + '0';
}
if (y + 1 < 9) {
dfs(str, x, y + 1);
}
else {
dfs(str, x + 1, 0);
}
if (found) {
return;
}
row[x] ^= (1 << i);
column[y] ^= (1 << i);
block[x/3][y/3] ^= (1 << i);
str[x][y] = '0';
}
}
void fun(vector<string> str) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
int v = str[i][j] - '0';
if (v > 0) {
row[i] |= (1 << v);
column[j] |= (1 << v);
block[i/3][j/3] |= (1 << v);
}
}
}
dfs(str, 0, 0);
}
int main()
{
vector<string> str;
str.push_back("005300000");
str.push_back("800000020");
str.push_back("070010500");
str.push_back("400005300");
str.push_back("010070006");
str.push_back("003200080");
str.push_back("060500009");
str.push_back("004000030");
str.push_back("000009700");
fun(str);
return 0;
}