博客
关于我
回溯法解数独
阅读量: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/

你可能感兴趣的文章
Pandas:将一列与数据帧的所有其他列进行比较
查看>>
PANDA:基于多列对数据表的行运行计算,并将输出存储在新列中
查看>>
PandoraFMS 监控软件 SQL注入漏洞复现
查看>>
PandoraFMS 监控软件 任意文件上传漏洞复现
查看>>
PanTools多网盘登录神器
查看>>
Papyrus项目常见问题解决方案
查看>>
Parallel.ForEach使用示例
查看>>
Parallel.ForEach的基础使用
查看>>
parallels desktop for mac安装虚拟机 之parallelsdesktop密钥 以及 parallels desktop安装win10的办公推荐可以提高办公效率...
查看>>
parallelStream导致LinkedList遍历时空指针的问题
查看>>
Parameter ‘password‘ not found. Available parameters are [md5String, param1, username, param2]
查看>>
ParameterizedThreadStart task
查看>>
Paramiko exec_命令的实时输出
查看>>
Spring security之管理session
查看>>
paramiko模块
查看>>
param[:]=param-lr*param.grad/batch_size的理解
查看>>
spring mvc excludePathPatterns失效 如何解决spring拦截器失效 excludePathPatterns忽略失效 拦截器失效 spring免验证拦截器不起作用
查看>>
Spring Cloud 之注册中心 EurekaServerAutoConfiguration源码分析
查看>>
Parrot OS 6.2 重磅发布!推出全新 Docker 容器启动器
查看>>
Parrot OS 6.3 发布!全面提升安全性,新增先进工具,带来更高性能
查看>>