回溯法求解数独(C++实现)

回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。

#include <iostream>
#include <algorithm>
using namespace std;
int map[9][9];
bool isPlace(int count){
	int row = count / 9;
	int col = count % 9;
	int j;
	//同一行
	for(j = 0; j < 9; ++j){
		if(map[row][j] == map[row][col] && j != col){
			return false;
		}
	}
	//同一列
	for(j = 0; j < 9; ++j){
		if(map[j][col] == map[row][col] && j != row){
			return false;
		}
	}
	//同一小格
	int tempRow = row / 3 * 3;
	int tempCol = col / 3 * 3;
	for(j = tempRow; j < tempRow + 3;++j){
		for(int k = tempCol; k < tempCol + 3; ++k){
			if(map[j][k] == map[row][col] && j != row && k != col){
				return false;
			}
		}
	}
	return true;
}
void backtrace(int count){
	if(count == 81){
		cout<<"结果:"<<endl;
		for(int i = 0; i < 9; ++i){
			for(int j =  0; j < 9; ++j){
				cout<<map[i][j]<<" ";
			}
			cout<<endl;
		}
		return;
	}
	int row = count / 9;
	int col = count % 9;
	if(map[row][col] == 0){
		for(int i = 1; i <= 9; ++i){
			map[row][col] = i;//赋值
			if(isPlace(count)){//可以放
				backtrace(count+1);//进入下一层
			}
		}
		map[row][col] = 0;//回溯
	}else{
		backtrace(count+1);
	}
}
int main()
{
	for(int i = 0; i < 9; ++i){
		for(int j = 0; j < 9; ++j){
			cin>>map[i][j];
		}
	}
	backtrace(0);
	return 0;
}

测试数据:

8 0 0 0 0 0 0 0 1
9 0 0 0 2 0 0 0 3
0 3 0 0 5 0 0 7 0
0 0 5 0 0 0 4 0 0 
0 0 4 5 0 9 6 0 0
0 0 0 8 0 1 0 0 0 
0 0 0 0 0 0 0 0 0
0 4 6 0 0 0 8 2 0
0 2 0 3 0 5 0 9 0

运行结果:

同样利用到回溯求解的有: ACM入门之杭电1045:Fire Net C++解法
  • 6
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值