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

你可能感兴趣的文章
MyEcplise中SpringBoot怎样定制启动banner?
查看>>
MyPython
查看>>
MTD技术介绍
查看>>
MySQL
查看>>
MySQL
查看>>
mysql
查看>>
MTK Android 如何获取系统权限
查看>>
MySQL - 4种基本索引、聚簇索引和非聚索引、索引失效情况、SQL 优化
查看>>
MySQL - ERROR 1406
查看>>
mysql - 视图
查看>>
MySQL - 解读MySQL事务与锁机制
查看>>
MTTR、MTBF、MTTF的大白话理解
查看>>
mt_rand
查看>>
mysql -存储过程
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>