软件工程实践2019第三次作业

使用回溯算法求解数独
核心算法:
int findNextValue(int rowIndex, int colIndex, int start) {
int index = findIndex(rowIndex, colIndex);// 找到所在的宫
for (int i = start; i < 9; i++) {
if (rule[0][rowIndex][i]) continue;
if (rule[1][colIndex][i]) continue;
if (rule[2][index][i]) continue;
return i;
}
return -1;
}

修改占用状态的函数changRule

void changeRule(int rowIndex, int colIndex, int style) {
int index = findSmallIndex(rowIndex, colIndex);
int value = sudoku[rowIndex][colIndex];
rule[0][rowIndex][value] = style;
rule[1][colIndex][value] = style;
rule[2][index][value] = style;
}
初始化函数
void initSudoku() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
sudoku[i][j] = getchar() - '0' - 1;
flag[i][j] = ~sudoku[i][j] ? 0 : 1;
if (!flag[i][j]) changeRule(i, j, 1);
}
getchar();
}
}
主要求解函数
void solve(int rowIndex, int colIndex) {
if (colIndex == 9) {rowIndex++;colIndex = 0;}
while (rowIndex <= 8 && !flag[rowIndex][colIndex]) {
colIndex++;
if (colIndex == 9) {rowIndex++;colIndex = 0;}
}
if (rowIndex > 8) {show();return;}
while (~(sudoku[rowIndex][colIndex] = findNextValue(rowIndex, colIndex, sudoku[rowIndex][colIndex] + 1))) {
changeRule(rowIndex, colIndex, 1);
solve(rowIndex, colIndex + 1);
changeRule(rowIndex, colIndex, 0);
}
}

转载于:https://www.cnblogs.com/sz1936/p/11588274.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值