博客
关于我
回溯法解数独
阅读量: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_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>
MySQL 索引的面试题总结
查看>>
mysql 索引类型以及创建
查看>>
MySQL 索引连环问题,你能答对几个?
查看>>
Mysql 索引问题集锦
查看>>
Mysql 纵表转换为横表
查看>>
mysql 编译安装 window篇
查看>>
mysql 网络目录_联机目录数据库
查看>>
MySQL 聚簇索引&&二级索引&&辅助索引
查看>>
Mysql 脏页 脏读 脏数据
查看>>