Objective c 数独回溯算法失败
我正在尝试生成一个数独板,虽然我可以生成一个解决方案,但我现在需要删除用户可以填写的方块。为了做到这一点,我想使用回溯检查,每次我删除一个正方形,董事会是 1.仍然是可解的和2。只有一个解决方案 问题 当我在上测试回溯算法时(其中零是空的正方形),它返回。很明显,我不希望在第一排有几个9 我的代码Objective c 数独回溯算法失败,objective-c,algorithm,sudoku,Objective C,Algorithm,Sudoku,我正在尝试生成一个数独板,虽然我可以生成一个解决方案,但我现在需要删除用户可以填写的方块。为了做到这一点,我想使用回溯检查,每次我删除一个正方形,董事会是 1.仍然是可解的和2。只有一个解决方案 问题 当我在上测试回溯算法时(其中零是空的正方形),它返回。很明显,我不希望在第一排有几个9 我的代码 - (BOOL) solveArray: (NSArray*) numArray { NSMutableArray* board = [numArray mutableCopy]; f
- (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;
}
-(BOOL)solveArray:(NSArray*)numArray{
NSMutableArray*板=[numArray mutableCopy];
对于(int i=0;i每个递归级别都需要自己的行和列变量。也就是说,行和列应该是solveArray
的输入,而不是findunsignedLocation
的输出,而不是成员变量。因此,当存在回溯时,失败级别的行和列将被调用方重用
鉴于某些指定的位置正在被覆盖,可能findunsignedlocation
也包含错误
考虑到结果无效,可能possibleNumbersForRow
也包含错误。谢谢,我实际上重写了整个过程,所以我没有使用全局变量,我更改了您提到的两个函数,以便传递变量而不是使用全局变量。这正是我所需要的!