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.
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 != '') {
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);
}
}
}
}
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!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…