Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 14368 | Accepted: 7102 | Special Judge |
Description
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.
Input
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.
Output
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.
Sample Input
1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107
Sample Output
143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127
Source
http://bailian.openjudge.cn/practice/2982/
题目大意:就是数独咯,让你求解数独游戏,9乘9的矩阵要求每行每列和9个3*3的子矩阵内都出现数字1-9
题目分析:9乘9的矩阵,从第一个位置一直搜到最后一个位置,若当前位置有数字搜下一位置,否则枚举1-9并判断,
判断时当前行r = n/9当前列为c = n%9当前子矩阵的第一个元素位置为r / 3 * 3,c / 3 * 3
#include <cstdio>
char s[];
int num[][];
bool flag; bool ok(int n, int cur)
{
int r = n / ; //当前行
int c = n % ; //当前列
for(int j = ; j < ; j++) //枚举列
if (num[r][j] == cur)
return false;
for(int i = ; i < ; i++) //枚举行
if (num[i][c] == cur)
return false;
//得到当前所在的子矩阵的第一个元素位置
int x = r / * ;
int y = c / * ;
//枚举子矩阵中的元素
for(int i = x; i < x + ; i++)
for(int j = y; j < y + ; j++)
if (num[i][j] == cur)
return false;
return true;
} void DFS(int n)
{
if(n > || flag)
{
flag = true;
return;
}
if(num[n / ][n % ])//当前位置有数字直接搜索下一位
{
DFS(n + );
if(flag)
return;
}
else
{
for(int cur = ; cur <= ; cur++) //枚举数字
{
if(ok(n, cur)) //若ok则插入
{
num[n / ][n % ] = cur;
DFS(n + );
if(flag)
return;
num[n / ][n % ] = ; //还原
}
}
}
} int main()
{
int T;
scanf("%d", &T);
while(T--)
{
flag = false;
for(int i = ; i < ; i++) //得到数独矩阵
{
scanf("%s", s);
for(int j = ; j < ; j++)
num[i][j] = (s[j] - '');
}
DFS(); //从第一位开始搜
for(int i = ; i < ; i++)
{
for(int j = ; j < ; j++)
printf("%d", num[i][j]);
printf("\n");
}
}
}
题解来源:http://blog.csdn.net/tc_to_top/article/details/43699047