数独的解法c语言

/*************************************************************************
    > 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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值