Home > Software engineering >  C# recursive programming: jump onto previous step in code
C# recursive programming: jump onto previous step in code

Time:05-17

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?

CodePudding user response:

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;
  • Related