您的位置:首页 > 其它

poj 2676 sudoku dfs

2012-08-01 10:03 357 查看
Sudoku

Time Limit: 2000MSMemory Limit: 65536K
Total Submissions: 10299Accepted: 5141Special 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.
View Code

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

int sudoku[10][10],p[81][2];    //sudoku存放数独  p记录数独中的空格
int r[10][10],l[10][10],w[10][10];    //r[i][x]=1表示第i行已经有x这个数了,
//同理l[i][x]表示第i列已经有x这个数了 ,
//w[i][x] 表示第i个九宫个中已经有x这个数了。
int n,k;

int dfs(int x, int y)
{
int i,j;
if(n==k)
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
printf("%d",sudoku[i][j]);
}
printf("\n");
}
return 1;
}
for(i=1;i<=9;i++)
{
if(!r[x][i] && !l[y][i] && !w[x/3*3+y/3][i]){
sudoku[x][y]=i;
r[x][i]=l[y][i]=w[x/3*3+y/3][i]=1;
k++;
if(dfs(p[k][0],p[k][1])) return 1;
k--;
sudoku[x][y]=0;
r[x][i]=l[y][i]=w[x/3*3+y/3][i]=0;
}
}
return 0;
}

int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(r,0,sizeof(r));
memset(w,0,sizeof(w));
memset(l,0,sizeof(l));
int i,j;
k=0;
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
{
scanf("%1d",&sudoku[i][j]);
if(sudoku[i][j])
{
r[i][sudoku[i][j]]=1;
l[j][sudoku[i][j]]=1;
w[i/3*3+j/3][sudoku[i][j]]=1;
}
else
{
p[k][0]=i;
p[k][1]=j;
k++;
}
}
}
n=k;
k=0;
dfs(p[k][0],p[k][1]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: