Sudoku
Time Limit: 2000MS | Memory Limit: 65536K | |||
Total Submissions: 17913 | Accepted: 8674 | 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.
![](http://poj.meik.pw/images/2676_1.jpg)
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.
输出
为每个测试用例的程序应该在相同的格式打印解决方案作为输入数据。 空的细胞必须按照规定。 如果解决方案并不是唯一的,程序可以打印任何其中之一。
样例输入
1 103000509 002109400 000704000 300502006 060000050 700803004 000401000 009205800 804000107
样例输出
143628579 572139468 986754231 391542786 468917352 725863914 237481695 619275843 854396127
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int a[10][10], flag;
bool vis1[10],vis2[10],vis3[10];
bool check(int x, int y)
{
memset(vis1,0,sizeof(vis1));
memset(vis2,0,sizeof(vis2));
memset(vis3,0,sizeof(vis3));
for(int i = 1;i<=9;++i)
{
if(a[i][y]&&vis1[a[i][y]])return false;
else vis1[a[i][y]] = 1;
if(a[x][i]&&vis2[a[x][i]])return false;
else vis2[a[x][i]] = 1;
}
int aa, b;
if(x<=3)aa = 1;
else if(x<=6)aa = 4;
else aa = 7;
if(y<=3)b = 1;
else if(y<=6)b = 4;
else b = 7;
for(int i = aa;i<=aa+2;++i)
{
for(int j = b;j<=b+2;++j)
{
if(a[i][j]&&vis3[a[i][j]])
return false;
else vis3[a[i][j]] = 1;
}
}
return 1;
}
void dfs(int x, int y)
{
if(flag)return;
if(x>9)
{
x = 1;
y++;
}
if(x==1&&y==10)
{
flag = 1;
return;
}
if(a[x][y])dfs(x+1, y);
else
{
for(int i =1; i<=9;++i)
{
a[x][y] = i;
if(check(x,y))dfs(x+1, y);
if(flag)return;
}
a[x][y] = 0;
}
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
flag = 0;
for(int i = 1;i<=9;++i)
for(int j = 1;j<=9;++j)
scanf("%1d",&a[i][j]);
dfs(1, 1);
for(int i = 1;i<=9;++i)
{
for(int j = 1;j<=9;++j)
printf("%d", a[i][j]);
printf("\n");
}
}
return 0;
}