编程之美-构造数独(1)

回溯法:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int isShudu(int shudu[9][9], int i, int j)
{
	int k;
	int temp=shudu[i][j];
	int flag=1;
	for(k=0; k<9; ++k)
	{
		if (k!=i && shudu[k][j]==temp)
		{
			flag=0;
		}
	}


	for(k=0; k<9; ++k)
	{
		if (k!=j && shudu[i][k]==temp)
		{
			flag=0;
		}
	}

	int p = i/3;  
    int q = j/3; 
	int m;
	int n;
    for(m=p*3; m<p*3+3; m++)  
	{
        for(n=q*3; n<q*3+3; n++)  
		{
            if(m!=i && n!=j && shudu[m][n]==temp)
			{
                flag=0; 
			}
		}
	}

	return flag;
}

void outPut(int shudu[9][9])
{	
	int i;
	int j;
	for(i=0; i<9; ++i)
	{
		for (j=0; j<9; ++j)
		{
			printf("%d  ", shudu[i][j]);
		}
		printf("\n");
	}
}


int main()
{
	int shudu[9][9]={0};
	int i;
	int j;
	int k=0;

	srand(time(0));
	for (i=1; i<=9; ++i)
	{
		int temp=rand()%81;
		shudu[temp/9][temp%9]=i;
	}

	while (1)
	{
		i=k/9;
		j=k%9;

		while(1)
		{
			++shudu[i][j];

			if (shudu[i][j]>9)
			{
				shudu[i][j]=0;
				--k;
				break;
			}

			if (isShudu(shudu, i ,j)==1)
			{
				++k;
				break;
			}
		}
		
		if(81==k)
		{
			outPut(shudu);
			break;
		}
	}



	return 0;
}

 

posted @ 2012-05-09 11:21  徐露  阅读(469)  评论(0编辑  收藏  举报