/*
* File: 数独游戏算法,输入一个初始状态,如下图,0表示空
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107
结果如图
143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127
*
* Author: chenjiang
*
* Created on 2010年5月5日, 下午12:29
*/
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <stack>
#include <queue>
using namespace std;
int mapmap[10][10]; //保存整个
bool row[10][10], col[10][10], small_squre[10][10];
struct node {//定义一个点
int x, y;
};
stack<node>S;//定义一个栈,用于保存空格子
int get_squre(int x, int y) {//获得(x,y)所在小方格的序号
return x / 3 * 3 + y / 3;
}
bool Ok(int x, int y, int k) {//判断x行有没有数字k,y列有没有数字k,(x,y)所在的小方格有没有数字k
if (!row[x][k] && !col[y][k] && !small_squre[get_squre(x, y)][k])return 1;
else return 0;
}
bool dfs() {//深搜
int i, k;
if (!S.empty()) {
node temp = S.top();
S.pop();
for (i = 1; i <= 9; i++) {
if (Ok(temp.x, temp.y, i)) {
row[temp.x][i] = 1;
col[temp.y][i] = 1;
small_squre[get_squre(temp.x, temp.y)][i] = 1;
if (dfs()) {
mapmap[temp.x][temp.y] = i;
return 1;
} else {
row[temp.x][i] = 0;
col[temp.y][i] = 0;
small_squre[get_squre(temp.x, temp.y)][i] = 0;
}
}
}
S.push(temp);
return 0;
}
return 1;
}
/*
*
*/
int main(int argc, char** argv) {
int i, j, k;
char ch[10];
memset(row, 0, sizeof (row));
memset(col, 0, sizeof (col));
memset(small_squre, 0, sizeof (small_squre));
while (!S.empty())S.pop();
for (i = 0; i < 9; i++) {//0到8
scanf("%s", ch);//每一行输入一个字符串,表示当前行的数字
getchar();
for (j = 0; j < 9; j++) {//
k = ch[j] - '0';
mapmap[i][j] = k;
if (k) {
row[i][mapmap[i][j]] = 1;
col[j][mapmap[i][j]] = 1;
small_squre[get_squre(i, j)][mapmap[i][j]] = 1;
} else {
node N;
N.x = i;
N.y = j;
S.push(N);
}
}
}
dfs();//搜索
/*打印结果*/
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
cout << mapmap[i][j]<<" ";
}
cout << endl;
}
return (EXIT_SUCCESS);
}