objective-c - 数独回溯算法失败

标签 objective-c algorithm sudoku

我正在尝试生成一个数独板,虽然我可以生成一个解决方案,但我现在需要删除用户随后可以填写的方 block 。为了做到这一点,我想使用回溯来检查每次我移除一个正方形时,棋盘就是 1. 仍然可解且 2. 只有一个解。

问题

当我在 this board 上测试我的回溯算法时(其中零是空方 block ),它返回 this solution .例如,显然我不希望在第一行以几个 9 结尾。

我的代码

- (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;
}

关于我可能哪里出错的任何想法?

最佳答案

每一层递归都需要有自己的行和列变量。也就是说,行和列应该是 solveArray 的输入和 findUnassignedLocation 的输出,而不是成员变量。事实上,当存在回溯时,失败级别的行和列会被调用者重用。

鉴于某些分配的位置正在被覆盖,可能 findUnassignedLocation 也包含错误。

鉴于结果无效,可能 possibleNumbersForRow 也包含错误。

关于objective-c - 数独回溯算法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22201001/

相关文章:

objective-c - 以日/月/年格式显示特定日期的倒计时

ios - NSArray 中的 NSObjects 的属性是否发生变化,或者它们是否必须再次添加到 NSArray?

c - 在 C 中生成数独板

c# - 使用 PileExclusion 解决数独难题

java - 设置数独单元格的颜色

ios - 在 Textview 中添加 Carousel View

objective-c - 在 `CTFontManagerRegisterFontsForURL` 获取异常

c++ - 面试谜题: Sorting a million number input with limited memory

algorithm - 在字符串缓冲区/段落/文本中查找单词

algorithm - 查找数字之和为质数的数字