您的位置:首页 > 其它

Poj 2676 Sudoku

2012-01-17 13:53 267 查看
题目大意:9*9的数独问题,要求填写1到9的数字,使得每一行,每一列以及3*3的小矩阵中1到9各出现一次。

思路:DFS,根据坐标可以获取当前位置属于哪一行,哪一列以及哪一个3*3矩阵,同时应该注意做标记的效率。

#include <stdio.h>
#include <string.h>
#include <memory.h>
int t;
int data[12][12];
int row [12][12];
int col[12][12];
int square[12][12];
int x[90];
int y[90];
char num;
int ctr,flag;
int get_square_num(int i,int j) {
if (i>=1&&i<=3) {
if (j>=1&&j<=3)
return 1;
else if (j>=4&&j<=6)
return 2;
else
return 3;
}
else if (i>=4&&i<=6) {
if (j>=1&&j<=3)
return 4;
else if (j>=4&&j<=6)
return 5;
else
return 6;
}
else {
if (j>=1&&j<=3)
return 7;
else if (j>=4&&j<=6)
return 8;
else
return 9;
}
}
void DFS(int p) {
int temp,i,j,m;
if (flag==1)
return;
if (p==ctr) {
flag=1;
return;
}
i=x[p];
j=y[p];
temp=get_square_num(i,j);
//	printf("%d %d %d\n",i,j,temp);
for (m=1;m<=9;m++) {
if (row[i][m]==0&&col[j][m]==0&&square[temp][m]==0) {
data[i][j]=m;
row[i][m]=1;
col[j][m]=1;
square[temp][m]=1;
DFS(p+1);
if (flag==1)/*此处不大理解,需要注意*/
return;
//	data[i][j]=0;
row[i][m]=0;
col[j][m]=0;
square[temp][m]=0;
}
}
}
int main()
{
int i,j,temp;

scanf("%d",&t);
getchar();
while (t--) {
ctr=0;
flag=0;
memset(row,0,sizeof(row));
memset(col,0,sizeof(col));
memset(square,0,sizeof(square));
for (i=1;i<=9;i++) {
for (j=1;j<=9;j++) {
scanf("%c",&num);
data[i][j]=num-'0';
if (data[i][j]==0) {
x[ctr]=i;
y[ctr]=j;
ctr++;
}
else {
//	printf("888888888\n");
temp=get_square_num(i,j);
row[i][data[i][j]]=1;
col[j][data[i][j]]=1;
square[temp][data[i][j]]=1;
}
}
getchar();
}

DFS(0);
for (i=1;i<=9;i++) {
for (j=1;j<=9;j++) {
printf("%d",data[i][j]);
}
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: