您的位置:首页 > 其它

[poj 2676] Sudoku DFS

2016-03-28 15:11 369 查看
Sudoku

Time Limit: 2000MS Memory Limit: 65536K

Total Submissions: 17035 Accepted: 8286 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

题解:

简单dfs;

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int lin[10][10];
int vis[10][10][10],row[10][10];
char s[10][15];
int numx[82],numy[82];
int tot,flag=0;
int ma[10][10];
void dfs(int x)
{

if(x==tot+1)
{
flag=1;
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
printf("%d",ma[i][j]);
printf("\n");
}
return ;
}
if(flag) return ;
int xx=numx[x];
int yy=numy[x];
//if(x==1) cout<<row[1][4]<<"    "<<lin[2][4]<<"    "<<vis[(1-1)/3][(2-1)/3][4]<<endl;
for(int i=1;i<=9;i++)
if(lin[xx][i]==0&&row[yy][i]==0&&vis[(xx-1)/3][(yy-1)/3][i]==0)
{

lin[xx][i]=1,row[yy][i]=1,vis[(xx-1)/3][(yy-1)/3][i]=1;
ma[xx][yy]=i;
dfs(x+1);
lin[xx][i]=0,row[yy][i]=0,vis[(xx-1)/3][(yy-1)/3][i]=0;
}

}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
flag=0;
tot=0;
memset(lin,0,sizeof(lin));
memset(vis,0,sizeof(vis));
memset(row,0,sizeof(row));
for(int i=1;i<=9;i++)
{
scanf("%s",s[i]);
for(int ii=0;ii<9;ii++)
{
int tt=s[i][ii]-'0';

ma[i][ii+1]=tt;
if(tt==0)
{
tot++;
numx[tot]=i;
numy[tot]=ii+1;
continue;
}
lin[i][tt]=1;
//if(ii+1==2) cout<<"   "<<row[2][4]<<endl;
row[ii+1][tt]=1;
vis[(i-1)/3][(ii)/3][tt]=1;
}
}

dfs(1);

if(!flag)
for(int i=1;i<=9;i++)
printf("%s\n",s[i]);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: