[英]Sudoku Recursive Backtrack Aid in C
I am relatively new to coding and recursion has been a thorn in my side.我对编码比较陌生,递归一直是我的眼中钉。 I need help with implementing backtrack recursion.
我需要帮助实现回溯递归。
Here is my sample code (Assume all helper functions work correctly [and they do])这是我的示例代码(假设所有辅助函数都正常工作 [并且他们确实如此])
void solve_sudoku(char sudoku[9][9])
{
if (contains_empty_cell(sudoku) == 1)
{
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
if (sudoku[y][x] == 0)
{
for (int i = 1; i <= 9; i++)
{
sudoku[y][x] = i;
if (is_valid_column(sudoku, y, x) == 1 &&
is_valid_row(sudoku, y, x) == 1 &&
is_valid_sub_box(sudoku, y, x) == 1)
{
solve_sudoku(sudoku);
}
}
if (sudoku[y][x] == 9)
{
sudoku[y][x] = 0;
return;
}
}
}
}
}
}
I think you are close.我认为你很接近。 The main problem is how you are handling a solution.
主要问题是您如何处理解决方案。 It seems you tried to handle it with
if (sudoku[y][x] == 9)
.您似乎试图用
if (sudoku[y][x] == 9)
来处理它。 But that's not correct.但那是不正确的。
Option 1 is to exit once a solution is found.选项 1 是在找到解决方案后退出。
solve_sudoku()
returns a value to indicate so. solve_sudoku()
返回一个值来表明这一点。 The solution will be the end result after the outermost call of solve_sudoku()
:解决方案将是最外层调用
solve_sudoku()
之后的最终结果:
int solve_sudoku(char sudoku[9][9])
{
if (contains_empty_cell(sudoku) != 0)
{
return 1; // sudoku completely filled in, i.e. solution found
}
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
if (sudoku[y][x] == 0)
{
for (int i = 1; i <= 9; i++)
{
sudoku[y][x] = i;
if (is_valid_column(sudoku, y, x) == 1 &&
is_valid_row(sudoku, y, x) == 1 &&
is_valid_sub_box(sudoku, y, x) == 1)
{
if (solve_sudoku(sudoku) == 1)
{
return 1; // exit if solution found
}
}
}
// restore empty cell
sudoku[y][x] = 0;
}
}
}
return 0;
}
A Sudoku can have multiple solutions.一个数独可以有多种解法。 So option 2 is to print each found solution and then continue:
所以选项 2 是打印每个找到的解决方案,然后继续:
void solve_sudoku(char sudoku[9][9])
{
if (contains_empty_cell(sudoku) == 0)
{
// Sudoku completely filled in, print solution
print_solution(sudoku);
return;
}
for (int y = 0; y < 9; y++)
{
for (int x = 0; x < 9; x++)
{
if (sudoku[y][x] == 0)
{
for (int i = 1; i <= 9; i++)
{
sudoku[y][x] = i;
if (is_valid_column(sudoku, y, x) == 1 &&
is_valid_row(sudoku, y, x) == 1 &&
is_valid_sub_box(sudoku, y, x) == 1)
{
solve_sudoku(sudoku);
}
}
// restore empty cell
sudoku[y][x] = 0;
}
}
}
}
I haven't tried it.我没试过。 So it might not be a complete solution.
所以它可能不是一个完整的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.