递归方法暴力求解数独

递归方法暴力求解数独,第1张

递归方法暴力求解数独
#include 
#include 
#include

using namespace std;

void SetColor(unsigned short ForeColor=7, unsigned short BackGroundColor=0)
{
	HANDLE hCon = GetStdHandle( STD_OUTPUT_HANDLE );
	SetConsoleTextAttribute( hCon, ForeColor | BackGroundColor );
}


int print(int *a, int *b)
{
	int i, j;

	cout << "┏━━━┳━━━┳━━━┳━━━┳━━━┳━━━┳━━━┳━━━┳━━━┓" ;
	cout << endl;

	for ( i = 0; i < 9; i ++ ) {
		for ( j = 0; j < 9; j ++ ) {
			if ( (a[i*9+j] == 0) && (b[i*9+j] == 0) ) {
				cout << "┃   ";
			}
			else if ( b[i*9+j] != 0 ) {
				cout << "┃ ";
				cout << b[i*9+j] << " "; 
			}
			else if ( a[i*9+j] != 0 ) {
				cout << "┃ ";
				SetColor(  4 );
				cout << a[i*9+j] << " "; 
				SetColor( 15 );
			}
		}
		cout << "┃" << endl;

		if ( i != 8 ) {
			cout << "┣━━━╋━━━╋━━━╋━━━╋━━━╋━━━╋━━━╋━━━╋━━━┫";
			cout << endl;
		}
		else {
			cout << "┗━━━┻━━━┻━━━┻━━━┻━━━┻━━━┻━━━┻━━━┻━━━┛";
			cout << endl;
		}
	}

	return 0;
}


int check(int *in, int x, int y, int t)
{
	int i, j, row, col;

	for ( i = 0; i < 9; i ++ )
		if ( (in[x*9+i] == t) || (in[i*9+y] == t) )
			return 0;

	row = x / 3 * 3;
	col = y / 3 * 3;
	for ( i = row; i < row+3; i ++ )
		for ( j = col; j < col+3; j ++ )
			if ( in[i*9+j] == t )
				return 0;

	return 1;
}


void solve(int *in, int *sol, int n)
{
	
	

	
	int x,y,i;
	x=n/9;
	y=n%9;
	if(n==81)
	{
		print(in,sol);
	}
	else if(sol[n]==0)
	{
		for(i=1;i<10;i++)
		{
			if(check(in,x,y,i))
			{
				in[n]=i;
				solve(in,sol,n+1);
			}
		}
		in[n]=0;
	}
	else
	{
		solve(in,sol,n+1);
	}
	

	return;
}

int main()
{

	int a[9][9] = {
	0,0,0,0,0,1,0,0,7,
		0,0,0,0,0,9,2,3,1,
		0,2,0,0,8,0,0,5,0,
		7,6,0,0,0,0,0,0,8,
		0,0,0,2,0,4,0,0,0,
		9,0,0,0,0,0,0,1,6,
		0,7,0,0,4,0,0,6,0,
		5,3,9,8,0,0,0,0,0,
		8,0,0,9,0,0,0,0,0};













	int b[9][9];

	
	for ( int i = 0; i < 9; i ++ )
		for ( int j = 0; j < 9; j ++ )
			b[i][j] = a[i][j];

	
	solve( &a[0][0], &b[0][0], 0 );

	
	system( "pause" );
	return 0;
}

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5651749.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存