欢迎来到IT嘟嘟的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

sudoku_solve数独算法

数独规则

首先看一下数独

数独的规则比较简单:

  • 每一行包括了1到9的数字,并且不能重复。
  • 每一列包括了1到9的数字,并且不能重复。
  • 每一组包括了1到9的数字,并且不能重复。

数独题的基本要求:
数独题的要求为数独要有唯一解,表现在:

  • 已填满的空格不能与它所在的行、列、组重合。
  • 采用遍历的方式能够找到数独的解,并且解是唯一的。

生成数独题的步骤和流程图

步骤

  • 步骤一、生成一个所有单元都是空的空数独
  • 步骤二、随机选择一个空单元,找到它的所有可能解
  • 步骤三、遍历空单元的每个可能解。将每个解填入,求的填入后数独的解的个数。
  • 步骤四、如果有可能解的填入之后数独解个数为1,则此填入此可能解之后的数独即为生成的数独,否则,随机选择一个可能解,进行步骤二。
    代码
#include<iostream>
using namespace std;
///N=9;
int n = 9;
bool isPossible(int mat[][9], int i, int j, int no){
	///Row or col nahin hona chahiye
	for (int x = 0; x<n; x++){
		if (mat[x][j] == no || mat[i][x] == no){
			return false;
		}
	}
	/// Subgrid mein nahi hona chahiye
	int sx = (i / 3) * 3;
	int sy = (j / 3) * 3;

	for (int x = sx; x<sx + 3; x++){
		for (int y = sy; y<sy + 3; y++){
			if (mat[x][y] == no){
				return false;
			}
		}
	}
	return true;
}
void printMat(int mat[][9])
{
	for (int i = 0; i<n; i++){
		for (int j = 0; j<n; j++){
			cout << mat[i][j] << " ";
			if ((j + 1) % 3 == 0){
				cout << '\t';
			}
		}
		if ((i + 1) % 3 == 0){
			cout << endl;
		}
		cout << endl;
	}
}
bool solveSudoku(int mat[][9], int i, int j){
	///Base Case
	if (i == 9){
		///Solve kr chuke hain for 9 rows already
		printMat(mat);
		return true;
	}
	///Crossed the last  Cell in the row
	if (j == 9){
		return solveSudoku(mat, i + 1, 0);
	}
	///Blue Cell - Skip
	if (mat[i][j] != 0){
		return solveSudoku(mat, i, j + 1);
	}
	///White Cell
	///Try to place every possible no
	for (int no = 1; no <= 9; no++){
		if (isPossible(mat, i, j, no)){
			///Place the no - assuming solution aa jayega
			mat[i][j] = no;
			bool aageKiSolveHui = solveSudoku(mat, i, j + 1);
			if (aageKiSolveHui){
				return true;
			}
			///Nahin solve hui
			///loop will place the next no.
		}
	}
	///Sare no try kr liey, kisi se bhi solve nahi hui
	mat[i][j] = 0;
	return false;
}
int main(){
	int mat[9][9] =
	{ { 5, 3, 0, 0, 7, 0, 0, 0, 0 },
	{ 6, 0, 0, 1, 9, 5, 0, 0, 0 },
	{ 0, 9, 8, 0, 0, 0, 0, 6, 0 },
	{ 8, 0, 0, 0, 6, 0, 0, 0, 3 },
	{ 4, 0, 0, 8, 0, 3, 0, 0, 1 },
	{ 7, 0, 0, 0, 2, 0, 0, 0, 6 },
	{ 0, 6, 0, 0, 0, 0, 2, 8, 0 },
	{ 0, 0, 0, 4, 1, 9, 0, 0, 5 },
	{ 0, 0, 0, 0, 8, 0, 0, 7, 9 } };
	printMat(mat);
	cout << "Solution " << endl;
	solveSudoku(mat, 0, 0);
	system("pause");
	return 0;
}

 

 

 

 

posted on 2019-08-24 10:32  IT嘟嘟  阅读(579)  评论(0编辑  收藏  举报

导航