#include <iostream>
using namespace std;
class Sudoku {
private:
int data[9][9] = { 0 };
//保存空格信息(坐标、试到哪个数了)及长度
int flag[81][3] = { 1 };
int length = 0;
//判断该坐标上是否能放num这个数
bool suitable(int i, int j, int num) {
if (num == 10) {
return false;
}
//判断行列及一个九宫格内是否重复
for (int k = 0; k < 9; k++) {
if ((data[i][k] == num) || (data[k][j] == num)) {
return false;
}
}
int a = (i / 3) * 3, b = (j / 3) * 3;
for (int k = a; k < a + 3; k++) {
for (int l = b; l < b + 3; l++) {
if (data[k][l] == num) {
return false;
}
}
}
return true;
}
public:
Sudoku() {
//读入初始化状态,并将空白格坐标填入flag
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cin >> data[i][j];
if (data[i][j] == 0) {
flag[length][0] = i;
flag[length][1] = j;
length++;
}
}
}
}
void printData() {
cout << endl;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
cout << data[i][j] << " ";
if ((j + 1) % 3 == 0) {
cout << " ";
}
}
cout << endl;
if ((i + 1) % 3 == 0) {
cout << endl;
}
}
}
void solve() {
for (int i = 0; i < length; i++) {
if (data[flag[i][0]][flag[i][1]] != 0) {
data[flag[i][0]][flag[i][1]] = 0;
flag[i][2]++;
}
bool f = true;
while (!suitable(flag[i][0], flag[i][1], flag[i][2])) {
flag[i][2]++;
if (flag[i][2] >= 10) {
flag[i][2] = 1;
i = i - 2;
f = false;
break;
}
}
if (f == true) {
data[flag[i][0]][flag[i][1]] = flag[i][2];
}
}
}
};
int main() {
Sudoku s;
s.solve();
s.printData();
return 0;
}
/*
测试用例
9 5 0 0 0 4 0 0 8
2 4 6 0 7 0 0 5 9
7 8 0 6 0 9 2 3 4
8 6 0 7 1 3 0 0 2
3 0 0 0 0 0 0 0 7
1 0 0 9 4 2 0 8 3
5 9 8 2 0 6 0 7 1
4 1 0 0 8 0 3 9 6
6 0 0 4 0 0 0 2 5
6 0 0 3 0 5 0 2 0
8 4 2 0 6 0 0 0 0
0 0 0 0 2 0 1 0 6
0 9 0 0 0 0 8 6 2
0 3 0 8 0 2 0 0 9
0 0 8 1 0 0 0 7 0
0 2 0 0 1 0 0 0 5
5 0 3 0 7 0 6 0 0
0 0 0 9 0 3 0 4 0
5 0 0 0 0 0 0 4 8
0 6 0 0 4 0 0 0 0
0 0 0 0 3 5 0 2 0
0 0 9 0 5 0 7 0 0
0 0 0 9 0 0 6 0 0
8 0 0 2 7 0 0 0 0
0 0 0 0 0 1 0 0 7
4 0 8 0 0 0 0 0 5
0 0 3 4 0 9 0 0 0
*/
蛤蛤这个还挺有意思的,老妈突然又玩起数独了,奈何玩不过她,只好自己动手丰衣足食。倒也没想象中麻烦,我这用的是暴力的方法,每个空白格子都从1-9去试,1-9都不行则倒回上一个空白格继续试。理论上用递归写的会更加简洁,奈何我写递归总是反应不过来,最后还是用循环写了。嗯,就这么多。