Start learning free

LESSON 410 OF 678 · BACKTRACKING

Sudoku

Practice O(nn2)

You get an unfinished Sudoku board with 9 rows and 9 columns. Each cell is a Character. It is a digit from '1' to '9', or '.' for an empty cell.

Return the board with every empty cell filled in.

The finished board must follow three rules:

  1. Each row holds the digits 1 to 9 once.
  2. Each column holds the digits 1 to 9 once.
  3. Each 3 x 3 block holds the digits 1 to 9 once. The thick lines in the picture below mark the nine blocks.

The digits already on the board stay where they are.

 

Example 1:

382 132 745 567 657134 784 326 685 572

Input: board = [
  [".","3","8",".",".","2",".",".","."],
  [".","1",".","3",".",".","2",".","."],
  [".",".",".",".","7","4","5",".","."],
  [".",".",".",".","5","6",".","7","."],
  ["6",".","5","7",".","1","3",".","4"],
  [".","7",".","8","4",".",".",".","."],
  [".",".","3","2","6",".",".",".","."],
  [".",".","6",".",".","8",".","5","."],
  [".",".",".","5",".",".","7","2","."]
]
Output: [
  ["5","3","8","6","9","2","4","1","7"],
  ["4","1","7","3","8","5","2","6","9"],
  ["2","6","9","1","7","4","5","3","8"],
  ["3","8","4","9","5","6","1","7","2"],
  ["6","9","5","7","2","1","3","8","4"],
  ["1","7","2","8","4","3","6","9","5"],
  ["9","5","3","2","6","7","8","4","1"],
  ["7","2","6","4","1","8","9","5","3"],
  ["8","4","1","5","3","9","7","2","6"]
]
Explanation: The puzzle is drawn above.
It has exactly one solution, drawn below.
The digits you add are in blue.


  
  
  
  
    382
    132
    745
    567
    657134
    784
    326
    685
    572
  
  
    569417
    478569
    269138
    384912
    928
    123695
    957841
    724193
    841396
  

 

Constraints:

  • The board is always 9 rows of 9 cells.
  • A cell is a digit from '1' to '9' or '.' (empty).
  • Every puzzle you get has exactly one solution.

STEP 1 OF 31
    Ctrl + Enter to check