【第二篇】数独终局

个人项目:生成数独终局并求解


注:这周时间不太充裕,内容相对较简略,详细内容之后更新。

四.设计实现

2.编码实现

(1)生成数独模块设计实现

生成数独主要由CreateSudoku函数来实现。
传入参数n,代表要生成的数独个数。
由解题思路可知,第一行的每一种排列,根据平移的规律,都对应着72个不同的矩阵,即1-3行的3两种平移方式,4-6行的6种平移方式,7-9行的6种平移方式。
因此,实现流程如下:

Created with Raphaël 2.2.0 开始 传入初始排列 矩阵个数是否<n 平移构建矩阵 矩阵个数是否<n 生成下一排列 结束 yes no yes no

其中,平移构建矩阵通过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,实现输出。


  1. 内容摘自官方文档:http://www.cplusplus.com/reference/algorithm/next_permutation/ ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值