C#递归编程:跳到代码的上一个步骤
我已经获得了编写一个Sudoku程序的任务,该程序解决了Sudoku Wikipedia示例。 解决Sudoku难题的方法必须是一种递归方法。 它首先检查了Sudoku板是否有效(Sudoku规则:在同一行,列和框中没有两次数字),然后获取可以写入的第一个空字段,并在字段中写入第一个值(数字1)。之后,该方法再次自称(递归)。
我的方法看起来像这样:
private bool SolveSudoku(int[,] board)
{
// if board not valid, return false
if (!CheckBoardValid(board))
{
return false;
}
// if board full, return true
var nextField = GetFirstEmpty(board);
if (nextField is null)
{
return true;
}
for (int value = 1; value < 10; value++)
{
board[nextField.Value.X, nextField.Value.Y] = value;
var solved = SolveSudoku(board);
// if solved, do nothing
// if not solved, undo this step and try writing next number (value++) in field
}
return false;
}
如果这是无效的,我该如何撤消最后一步?
I have been given the task to write a sudoku program, which solves the sudoku wikipedia example.
The method which solves the sudoku puzzle has to be a recursive method.
It first checks if the sudoku board is valid (sudoku rules: no twice occuring numbers in same row, column and box), then gets the first empty field it can write in and writes the first value (number 1) in field. After that, the method calls itself again (recursion).
My method looks like this:
private bool SolveSudoku(int[,] board)
{
// if board not valid, return false
if (!CheckBoardValid(board))
{
return false;
}
// if board full, return true
var nextField = GetFirstEmpty(board);
if (nextField is null)
{
return true;
}
for (int value = 1; value < 10; value++)
{
board[nextField.Value.X, nextField.Value.Y] = value;
var solved = SolveSudoku(board);
// if solved, do nothing
// if not solved, undo this step and try writing next number (value++) in field
}
return false;
}
How can I undo the last step, if it is not valid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
剥离相关部分:
Snipping out the relevant part: