首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数独回溯算法失败

数独回溯算法失败
EN

Stack Overflow用户
提问于 2014-03-05 14:45:31
回答 1查看 234关注 0票数 2

我正在尝试生成一个sudoku板,虽然我可以生成一个解决方案,但现在我需要删除用户可以填充的方块。为了做到这一点,我想使用回溯检查,每次我删除一个方块,板是1,仍然可以解决,2,只有一个解决方案。

问题

当我在这个板上测试我的回溯算法(其中零是空方格)时,它返回这个解决方案。显然,我不希望在第一行中出现几个9s,例如。

我的代码

代码语言:javascript
复制
- (BOOL) solveArray: (NSArray*) numArray {
    NSMutableArray* board = [numArray mutableCopy];
    for (int i=0; i<9; i++) { //make all of the arrays mutable as well (since it's 2D)
        [board replaceObjectAtIndex:i withObject:[board[i] mutableCopy]];
    }

    //if everything is filled in, it's done
    if (![self findUnassignedLocation:board]) {
        NSLog(@"\n%@", [SudokuBoard sudokuBoardWithArray:board]);
        return TRUE;
    }

    NSArray* poss = [[SudokuBoard sudokuBoardWithArray:board] possibleNumbersForRow:self.arow Col:self.acol];


    //if there are no options for a location, this didn't work.
    if ([poss count] == 0) {
        return FALSE;
    }

    //otherwise, continue recursively until we find a solution
    else {
        for (int i=0; i<[poss count]; i++) {
            //make a tentative assignment
            board[self.arow][self.acol] = poss[i];
            //return, if successful, done
            if ([self solveArray:board]) {
                return TRUE;
            }
            //if that didn't work, unmake it and retry with other options
            board[self.arow][self.acol] = [NSNumber numberWithInt:0];
        }
    }
    return FALSE;
}

对我可能出错的地方有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-06 00:41:36

每个递归级别都需要自己的行和列变量。也就是说,行和列应该是solveArrayfindUnassignedLocation输出的输入,而不是成员变量。实际上,当出现回溯失败级别的行和列时,调用方将重用它。

考虑到一些指定的位置正在被覆盖,也许findUnassignedLocation也包含一个错误。

假设结果无效,也许possibleNumbersForRow也包含一个错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22201001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档