POJ 2676 Sudoku
作者:互联网
POJ 2676 Sudoku
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
题解:
暴搜填数独。稍稍有一点进阶的暴搜。思路也很简单:尝试往里填数,然后暴力判断即可。
这个暴力判断可以用位运算优化一下.但是本题我并没有这么干,用了个bool数组。
需要提一嘴的是这个第几个九宫格的处理。式子已经打在代码里了,大家手画模拟一下就能看出来这个东西的正确性。
代码:
#include<cstdio>
#include<cstring>
using namespace std;
int t,cnt;
int mp[11][11];
char mapi[11][11];
bool flag;
bool row[11][11],col[11][11],grid[11][11];
void print()
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
printf("%d",mp[i][j]);
puts("");
}
}
void dfs(int x,int y)
{
if(flag)
return;
if(mp[x][y])
{
if(x==9&&y==9)
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
printf("%d",mp[i][j]);
puts("");
}
flag=1;
return;
}
if(y==9)
dfs(x+1,1);
else
dfs(x,y+1);
}
if(!mp[x][y])
{
int k=3*((x-1)/3)+(y-1)/3+1;
for(int i=1;i<=9;i++)
{
if(!row[x][i]&&!col[y][i]&&!grid[k][i])
{
row[x][i]=1;
col[y][i]=1;
grid[k][i]=1;
mp[x][y]=i;
if(x==9&&y==9)
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
printf("%d",mp[i][j]);
puts("");
}
flag=1;
puts("");
return;
}
if(y==9)
dfs(x+1,1);
else
dfs(x,y+1);
row[x][i]=0;
col[y][i]=0;
grid[k][i]=0;
mp[x][y]=0;
}
}
}
}
int main()
{
scanf("%d",&t);
while(t--)
{
memset(col,0,sizeof(col));
memset(row,0,sizeof(row));
memset(grid,0,sizeof(grid));
flag=0;
for(int i=1;i<=9;i++)
scanf("%s",mapi[i]+1);
for(int i=1;i<=9;i++)
for(int j=1;j<=9;j++)
{
mp[i][j]=mapi[i][j]-'0';
if(mp[i][j])
{
int k=3*((i-1)/3)+(j-1)/3+1;
row[i][mp[i][j]]=1;
col[j][mp[i][j]]=1;
grid[k][mp[i][j]]=1;
}
}
dfs(1,1);
}
return 0;
}
标签:11,Sudoku,cells,2676,digits,POJ,each,empty 来源: https://www.cnblogs.com/fusiwei/p/13838478.html