个人项目:生成数独终局并求解
注:这周时间不太充裕,内容相对较简略,详细内容之后更新。
四.设计实现
2.编码实现
(1)生成数独模块设计实现
生成数独主要由CreateSudoku函数来实现。
传入参数n,代表要生成的数独个数。
由解题思路可知,第一行的每一种排列,根据平移的规律,都对应着72个不同的矩阵,即1-3行的3两种平移方式,4-6行的6种平移方式,7-9行的6种平移方式。
因此,实现流程如下:
其中,平移构建矩阵通过move字符数组来实现:
char move1[10][5] = { "036","063" };//矩阵每三行的移动规则
char move2[10][5] = { "258","285","528","582","852","825" };//移动矩阵4-6行
char move3[10][5] = { "147","174","417","471","714","741" };//移动矩阵7-9行
生成下一排列可以选择手动生成,也可以选择采用C++的库函数。考虑到用库函数生成更高效率,代码采用库函数next_permutation实现,形如:
next_permutation(permutation, permutation + 8);
next_permutation的使用说明1如下:
Transform range to next permutationRearranges the elements in the range [first,last) into the next lexicographically greater permutation.
A permutation is each one of the N! possible arrangements the elements can take (where N is the number of elements in the range). Different permutations can be ordered according to how they compare lexicographicaly to each other; The first such-sorted possible permutation (the one that would compare lexicographically smaller to all other permutations) is the one which has all its elements sorted in ascending order, and the largest has all its elements sorted in descending order.
The comparisons of individual elements are performed using either operator< for the first version, or comp for the second.
If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If that was not possible (because it is already at the largest possible permutation), it rearranges the elements according to the first permutation (sorted in ascending order) and returns false.
同时,采用一个大数组保存生成的矩阵信息(在生成的过程中加入空格、换行等),以ofstream写入相应文件soduku.txt,实现输出。
内容摘自官方文档:http://www.cplusplus.com/reference/algorithm/next_permutation/ ↩︎