Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 18247 | Accepted: 8832 | 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.
![](https://i-blog.csdnimg.cn/blog_migrate/56e7e6182093bbca488d6c73ba833af6.jpeg)
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
题目大意:
/*
九宫格问题,也有人叫数独问题
把一个9行9列的网格,再细分为9个3*3的子网格,要求每行、每列、每个子网格内都只能使用一次1~9中的一个数字,即每行、每列、每个子网格内都不允许出现相同的数字。
*/用深搜一点一点的搜索.
这题的主要难点是如何判断符合条件的情况,避免发生符合答案但又回溯的问题,这里主要就是用一个值来判断,这个值就是图中原来给出的0的个数,也就是说当你完全符合要求并填满的时候就不需要回溯了.
具体看代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
struct node
{
int x;
int y;
}q[202];
int h[20][20];
bool row[20][10], col[20][10], squ[20][20][10];
int cnt, flag;
void init()
{
cnt = 0, flag = 0;
memset( row, false, sizeof(row) );
memset( col, false, sizeof(col) );
memset( squ, false, sizeof(squ) );
}
void dfs(int ant)
{
int i;
if ( ant < 0 )
{
flag = 1;return ;
}
int x = q[ant].x;
int y = q[ant].y;
for ( i = 1; i <= 9; i++ )
{
if (row[x][i] || col[y][i] || squ[x/3][y/3][i] )
continue;
row[x][i] = 1, col[y][i] = 1, squ[x/3][y/3][i] = 1;
h[x][y] = i;
dfs(ant-1);
if ( flag == 1 )
return ;
row[x][i] = 0, col[y][i] = 0, squ[x/3][y/3][i] = 0;
}
}
int main()
{
int i, j;
int T;
scanf ( "%d", &T );
while ( T-- )
{
init();
for ( i = 0;i < 9; i++ )
{
for ( j = 0;j < 9; j++ )
{
scanf ( "%1d" , &h[i][j] ) ;
int g = h[i][j];
if ( g != 0 )
{
row[i][g] = true, col[j][g] = true, squ[i/3][j/3][g] = true;
}
else
{
q[cnt].x = i, q[cnt++].y = j;
}
}
}
dfs(cnt-1);
for ( i = 0;i < 9; i++ )
{
for ( j = 0;j < 9; j++ )
{
printf ( "%d", h[i][j] );
}
printf ( "\n" );
}
}
return 0;
}
代码菜鸟,如有错误,请多包涵!!!
如有帮助记得支持我一下,谢谢!!!