/*************************************************************************
> File Name: sudu.c
> Author: ims
> Created Time: 2017年03月18日 星期六 23时41分10秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#define bool int
#define false 0
#define true 1
bool rUsed[9][10],cUsed[9][10],sUsed[9][10];
int pos[100];//record null position
int nullNum;
int table[9][9];
bool DFS_SUDO;
void print()
{
for(int i =0;i<9;i++)
{
for(int j =0;j<9;j++)
printf("%d",table[i][j]);
printf("\n");
}
}
void DFS(int n)
{
if(n>=nullNum)
{
DFS_SUDO=true;
print();///print result
return;
}
int r=pos[n]/9;
int c=pos[n]%9;
int k=(r/3)*3+(c/3); //the (r,c) is loacl in k st square
for(int i=1; i<=9 && !DFS_SUDO; i++)
{
if(cUsed[c][i]) continue; // determine whether it was used or not in column
if(rUsed[r][i]) continue; // determine whether it was used or not in row
if(sUsed[k][i]) continue; // determine whether it was used or not in square
cUsed[c][i]=rUsed[r][i]=sUsed[k][i]=true; //use it and record it is used in column,row,square
table[r][c]=i;
DFS(n+1);//var n plus 1 call DFS()
table[r][c]=0;
cUsed[c][i]=rUsed[r][i]=sUsed[k][i]=false;
}
return;
}
int main ()
{
FILE *fp;
int testCase;//num of input case
char line[10];
fp=fopen("data_sudu","r");
if(fp==NULL)
printf("no data_sudu file!");
fscanf(fp,"%d", &testCase);
fgetc(fp);
//printf("the num of case:%d\n",testCase);
while(testCase--)
{
nullNum=0;//num of null
for(int i=0;i<9;i++)
for(int j=0;j<10;j++)
rUsed[i][j]=cUsed[i][j]=sUsed[i][j]=false;
for(int i=0;i<9;i++)
{
fgets(line,11,fp);//read a line
for(int j=0;j<9;j++)
{
table[i][j]=line[j]-'0';
if(table[i][j])
{
rUsed[i][ table[i][j] ]=true;
cUsed[j][ table[i][j] ]=true;
int k =(i/3)*3 + (j/3);
sUsed[k][ table[i][j] ]=true;
}
else
pos[nullNum++]=9*i+j;//record null position
}
}
printf("the num of null position:%d\n",nullNum);
DFS_SUDO= false;
DFS(0);// call function DFS()
printf("\n");
}
fclose(fp);
return 0;
}
数独的解法c语言
最新推荐文章于 2022-03-28 18:46:39 发布