代码改变世界

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

2012-04-21 00:57  java线程例子  阅读(322)  评论(0编辑  收藏  举报

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

#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++解法