'C# recursive programming: jump onto previous step in code
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?
Solution 1:[1]
Snipping out the relevant part:
for (int value = 1; value < 10; value++)
{
board[nextField.Value.X, nextField.Value.Y] = value;
if(SolveSudoku(board)) return true;
// ^^ Stop if solved,
// iteration will increase value if not.
}
// reset and return false if no value for this field leads to a solution.
board[nextField.Value.X, nextField.Value.Y] = 0;
return false;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |