Sudoku is a very simple task. A square table with 9 rows and 9 columns is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task.
The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.
For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.
1 103000509 002109400 000704000 300502006 060000050 700803004 000401000 009205800 804000107
143628579 572139468 986754231 391542786 468917352 725863914 237481695 619275843 854396127
题目就是一个数独游戏,实用性很强,完成这道题目,数独游戏还不是so easy!!
代码:
#include<stdio.h>
#include<string.h>
using namespace std;
void Dfs(int x,int y);
void Getsuduku();
int suduku[9][10]; //存放数独
int H[9][10]; //标记是否在第 i行出现过
int L[9][10]; //标记是否在第 i 列出现过
int S[9][10]; //标记是否在第 i个小方块出现过
int isdone;
int main(){
int T;
scanf("%d",&T);
while(T--){
memset(suduku,0,sizeof(suduku));
memset(H,0,sizeof(H));
memset(L,0,sizeof(L));
memset(S,0,sizeof(S));
Getsuduku();
isdone=0;
Dfs(0,0);
}
return 0;
}
void Getsuduku(){
int i,j;
for(i=0;i<9;i++){
char temp[10];
scanf("%s",temp);
for(j=0;j<9;j++){
suduku[i][j]=temp[j]-'0'; //转化为数字
if(suduku[i][j]){
int k=i/3*3+j/3; //求出此时在第几个小方块里
H[i][suduku[i][j]]=1;
L[j][suduku[i][j]]=1;
S[k][suduku[i][j]]=1;
}
}
}
}
void Dfs(int x,int y){ //遍历每一点
if(x==9){
isdone=1;
int i,j;
for(i=0;i<9;i++){
for(j=0;j<9;j++)
printf("%d",suduku[i][j]);
printf("\n");
}
}
if(isdone) return ;
if(suduku[x][y]){
if(y==8) Dfs(x+1,0);
else Dfs(x,y+1);
}
else{
int num;
for(num=1;num<=9;num++){ //从 1 到 9 枚举数字
int k=x/3*3+y/3;
if(!L[y][num]&&!H[x][num]&&!S[k][num]){
suduku[x][y]=num;
L[y][num]=1;
H[x][num]=1;
S[k][num]=1;
if(y==8) Dfs(x+1,0);
else Dfs(x,y+1);
suduku[x][y]=0;
L[y][num]=0;
H[x][num]=0;
S[k][num]=0;
}
}
}
}