HardBacktrackingRecursionMatrixConstraint Satisfaction

1 approach, code in every language

Problem description

You are given a partially completed 9x9 Sudoku grid where empty cells are marked with the character '.'. Fill every empty cell with a digit from '1' to '9' so that the finished grid is valid: each row must contain the digits 1 through 9 without repetition, each column must do the same, and each of the nine 3x3 sub-grids must also contain every digit exactly once.

Modify the grid in place so it holds a complete, valid solution. The puzzle is guaranteed to have exactly one solution, so you do not need to handle ambiguous or unsolvable inputs.

Example 1

Input: board = [ ['5','3','.','.','7','.','.','.','.'], ['6','.','.','1','9','5','.','.','.'], ['.','9','8','.','.','.','.','6','.'], ['8','.','.','.','6','.','.','.','3'], ['4','.','.','8','.','3','.','.','1'], ['7','.','.','.','2','.','.','.','6'], ['.','6','.','.','.','.','2','8','.'], ['.','.','.','4','1','9','.','.','5'], ['.','.','.','.','8','.','.','7','9'] ]

Output: The same grid with every '.' replaced by a digit so that all rows, columns, and 3x3 blocks are valid.

Backtracking tries candidate digits for each blank cell and commits only to placements that keep the grid consistent, eventually producing the unique completed board.

Example 2

Input: board = [ ['.','.','9','7','4','8','.','.','.'], ['7','.','.','.','.','.','.','.','.'], ['.','2','.','1','.','9','.','.','.'], ['.','.','7','.','.','.','2','4','.'], ['.','6','4','.','1','.','5','9','.'], ['.','9','8','.','.','.','3','.','.'], ['.','.','.','8','.','3','.','2','.'], ['.','.','.','.','.','.','.','.','6'], ['.','.','.','2','7','5','9','.','.'] ]

Output: A fully filled 9x9 grid satisfying every row, column, and block constraint.

Each empty position is resolved by testing digits in order; whenever a partial assignment cannot lead to a solution, the search rewinds and tries the next digit.

Constraints

  • board.length == 9 and board[i].length == 9
  • Each cell holds a digit from '1' to '9' or the placeholder '.'
  • The input is guaranteed to have a single unique solution

After the pattern

Now solve one you haven't seen.

Complete the Planting Frame is our own problem on the technique behind Sudoku Solver: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free