博客
关于我
回溯法解数独
阅读量:738 次
发布时间:2019-03-21

本文共 1245 字,大约阅读时间需要 4 分钟。

数独问题解决方案代码实现

.documentElement > div<<问题解决方案的实现]]

include

include

using namespace std;

int map[9][9];string ch[9];

// 判断是否可以在指定位置放置数字bool isPlace(int count) {int row = count / 9;int col = count % 9;

// 检查同一行for(int j = 0; j < 9; j++) {    if(map[row][j] == map[row][col] && j != col) {        return false;    }}// 检查同一列for(int j = 0; j < 9; j++) {    if(map[j][col] == map[row][col] && j != row) {        return false;    }}// 检查同一3x3的小格int tempRow = row / 3 * 3;int tempCol = col / 3 * 3;for(int 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) {    backtrace(count + 1);} else {    // 检查能否在此位置放置数字    if(isPlace(count)) {        map[row][col] = 0;  // 确保这一步能走下去        backtrace(count + 1);    }}

}

// 主函数int main() {cin >> ch[0];for(int i = 0; i < 9; i++) {for(int j = 0; j < 9; j++) {map[i][j] = ch[i][j] - '0';}}backtrace(0);return 0;}

<'

转载地址:http://iexgz.baihongyu.com/

你可能感兴趣的文章
Puppet 在大规模分布式系统中的性能优化策略有哪些?
查看>>
puppet 学习总结(1)——puppet 入门详解
查看>>
puppet 集中化管理PDF by 守住
查看>>
Puppet---自动化运维工具(进阶)
查看>>
puppeteer(三)常用API
查看>>
PyTorch 微调终极指南:第 2 部分 — 提高模型准确性
查看>>
pure css做的手机页面
查看>>
PureMVC--一款多平台MVC框架
查看>>
pure框架
查看>>
putty、Xshell、远程连接、密钥登录
查看>>
Putty建立SSH隧道代理上网
查看>>
putty提示Network error:Software caused connection abort
查看>>
PyTorch 微调终极指南:第 1 部分 — 预训练模型及其配置
查看>>
PVE Win平台虚拟机下如何安装恢复自定义备份Win系统镜像ISO文件(已成功实现)
查看>>
PVS 6.1 Configuring Services Failed
查看>>
pv操作二
查看>>
PWA 入门指南:理解与构建现代化 Web 应用
查看>>
PWD的编译及调试
查看>>
PWM(Pulse Width Modulation)控制-ChatGPT4o作答
查看>>
PWM(Pulse Width Modulation,脉冲宽度调制)是什么
查看>>