问题描述
我正在学习 C,为此我决定编写一个数独求解器.我无法让解决函数返回已解决的板,我认为问题出在递归函数调用上.
I am learning C and to do so I decided to write a Sudoku solver. I am having trouble getting the solve function to return a solved board and my thought is the issue is with the recursive function call.
我将棋盘作为字符串传入,找到棋盘中第一个0"的索引,并使用该索引为该位置构建一个可能值列表.然后我迭代可能性,复制原始板,并用可能性替换零,然后将新板递归地传递给求解函数.代码如下:
I pass the board in as a string, find the index of the first "0" in the board and use that index to build a list of possible values for the position. I then iterate over the possibilities, copy the original board, and replace the zero with the possibility, then pass the new board recursively to the solve function. The code is below:
char *solve(char *board)
{
int zero = strcspn(board, "0");
if(zero > 80) {
return board;
} else {
char *possibilities = getPossibilities(zero, board);
if(possibilities != '\0') {
for(int i = 0; i < strlen(possibilities); i++) {
char *new_string = malloc(strlen(board) * sizeof(char));
memcpy(new_string, board, strlen(board));
new_string[zero] = possibilities[i];
return solve(new_string);
}
}
}
}
理想情况下,当字符串不再有任何0"时,函数应该返回.但是我得到了一些奇怪的输出,看起来像:
Ideally, the function should return when the string no longer has any "0"'s. However I am getting some weird output that looks like:
The string is �96245781100060004504810390007950043030080000405023018010630059059070830003590007
我在看问题时遇到了麻烦.该计划的完整要点是此处.我会喜欢任何输入.提前致谢!
I having trouble eyeing the problem. The full gist of the program is here. I would love any input. Thank you in advance!
推荐答案
char *new_string = malloc(strlen(board) * sizeof(char));
需要为'\0'终止符分配,并改为
you need to allocate for the '\0' terminating character, and change it to
char *new_string = malloc(strlen(board) + 1);
并将 memcpy
更改为 strcpy
char * strcpy(new_string, board);
这篇关于C中的递归不返回字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!