您的位置:首页 > 其它

poj(2676)——Sudoku

2017-08-11 00:02 323 查看
Sudoku

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


题意:

填充数独。倒搜快,但不清楚为什么。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;

char ma[10][10];
int map[10][10];

int vis_x[10][10],vis_y[10][10],f;

bool check(int x,int y,int v)
{
if(vis_x[x][v] || vis_y[y][v])return 0;

int xx=(x-1)/3*3,yy=(y-1)/3*3;
for(int i=xx+1;i<=xx+3;i++){
for(int j=yy+1;j<=yy+3;j++){
if(i==x&&j==y)continue;
if(map[i][j]==v)return 0;
}
}
map[x][y]=v;
return 1;
}

void dfs(int x,int y){
if(f)return ;
if(y==0&&x==1)
{
f=1;
for(int i=1;i<=9;i++){
for(int j=1;j<=9;j++)
printf("%d",map[i][j]);
printf("\n");
}
return ;
}
if(y<1){
x--;
y=9;
}

if(map[x][y])dfs(x,y-1);
else
for(int i=1;i<=9 && !map[x][y];i++)
{
if(check(x,y,i))
{
vis_x[x][i]=1;
vis_y[y][i]=1;
map[x][y]=i;
dfs(x,y-1);
vis_x[x][i]=0;
vis_y[y][i]=0;
map[x][y]=0;
}
}

}

int main(){
int tt;
scanf("%d",&tt);
while(tt--){
f=0;
memset(vis_x,0,sizeof(vis_x));
memset(vis_y,0,sizeof(vis_y));
for(int i=1;i<=9;i++){
scanf("%s",ma[i]);
for(int j=0;j<9;j++){
map[i][j+1]=ma[i][j]-'0';
if(map[i][j+1]){
vis_x[i][map[i][j+1]]=1;
vis_y[j+1][map[i][j+1]]=1;
}
}
}
// printf("-------------\n");
dfs(9,9);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM 数学 模拟 搜索 深搜