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

你可能感兴趣的文章
mysql 存储过程每隔一段时间执行一次
查看>>
mysql 存在update不存在insert
查看>>
Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
查看>>
Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
查看>>
Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
查看>>
Mysql 学习总结(89)—— Mysql 库表容量统计
查看>>
mysql 实现主从复制/主从同步
查看>>
mysql 审核_审核MySQL数据库上的登录
查看>>
mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
查看>>
mysql 导入导出大文件
查看>>
MySQL 导出数据
查看>>
mysql 将null转代为0
查看>>
mysql 常用
查看>>
MySQL 常用列类型
查看>>
mysql 常用命令
查看>>
Mysql 常见ALTER TABLE操作
查看>>
MySQL 常见的 9 种优化方法
查看>>
MySQL 常见的开放性问题
查看>>
Mysql 常见错误
查看>>
mysql 常见问题
查看>>