数独(回溯)

#include <iostream>
using namespace std;
void search(int step);
bool mark(int step);
int ans=0;
int a[9][9];
int main()
{
	int i,j;
	for (i=0;i<9;i++)
		for (j=0;j<9;j++)
			cin>>a[i][j];
	search(0);
	return 0;
}

void search(int step)
{
	int i,j;
	int row=step/9;//行 
	int col=step%9;//列 
	if (step==81) 
	{
		for (i=0;i<9;i++)
		{	
			for (j=0;j<9;j++)
				cout<<a[i][j];
			cout<<endl;
		}
	}
	else if (a[row][col]==0)
	{
		for (i=1;i<=9;i++)
		{
			a[row][col]=i;
			if (mark(step)) search(step+1);		
		}
		a[row][col]=0;//回溯 
	}
	else search(step+1);
}

bool mark(int step)//判断数字 
{
	int i,j;
	int row=step/9;
	int col=step%9;
	//判断行
	for  (i=0;i<9;i++)
		if (a[row][col]==a[row][i] && col!=i) return false;
	//判断列
	for (i=0;i<9;i++)
		if (a[row][col]==a[i][col] && row!=i) return false;
	//判断宫
	int tempRow=row/3*3;//每个宫的行 
	int tempCol=col/3*3;//每个宫的列 
	for (i=tempRow;i<tempRow+3;i++)
		for (j=tempCol;j<tempCol+3;j++)
			if (a[row][col]==a[i][j] && row!=i && col!=j) return false; 
	//如果都符合,则返回真 
	return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值