栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

递归方法暴力求解数独

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

递归方法暴力求解数独

#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;
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/649557.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号