Recursion and Backtracking Searching with constraints
332. Sudoku Solver
You are given a partly filled Sudoku board, board. Fill in every empty cell so that the board is solved.
Change the board in place. The function returns nothing.
A solved board has a digit from 1 to 9 in every cell, and each digit appears exactly once in every row,
every column and every box. The boxes are the nine 3 × 3 squares that rows 0–2, 3–5 and 6–8 make with
columns 0–2, 3–5 and 6–8. The digits already on the board must stay where they are.
The examples write the board as 9 strings, one per row, with . for an empty cell. Your function gets it as
a 9 × 9 grid of characters. In Python and JavaScript, that is a list of lists of one-character strings.
Every board has exactly one solution.
The result shows solved when the board you leave is full, breaks no rule and keeps every given digit.
Otherwise it shows the first thing wrong, such as cell (2, 5) is still empty or row 4 has two 7s. Rows
and columns are numbered from 0.
Example 1
Input: board = ["6.942.8..",
"...81.6..",
"4....6.5.",
"7...3...2",
"..1...5..",
"8...4...3",
".9.2....6",
"..8.74...",
"..3.894.5"]
["619425837",
"352817694",
"487396251",
"745938162",
"931762548",
"826541973",
"194253786",
"568174329",
"273689415"]Explanation: The board on the right is the only way to fill the 51 empty cells. Each row, column and box holds the digits 1 to 9 once, and the 30 given digits are where they started.
Example 2
Input: board = [".........",
"489126573",
"567398421",
"948612735",
"351879642",
"276435189",
"815243967",
"692587314",
"734961258"]
["123754896",
"489126573",
"567398421",
"948612735",
"351879642",
"276435189",
"815243967",
"692587314",
"734961258"]Explanation: The whole top row is empty, but every other row is full. Each column is missing one digit, and that digit goes in the top row.
Example 3
Input: board = ["4....8...",
"....2...7",
"68..5...9",
".......6.",
"..974....",
".129.....",
"...3...9.",
"........1",
"..5..64.."]
["427198356",
"591623847",
"683457129",
"754831962",
"869742513",
"312965784",
"176384295",
"248579631",
"935216478"]Explanation: Only 21 digits are given, and the board still has exactly one solution. Some cells cannot be decided by looking at their row, column and box alone, so a solver has to try a digit and go back when it leads nowhere.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
board.length = 9board[i].length = 9board[i][j]is one of'1'to'9', or'.'- No given digit repeats in a row, a column or a box.
- The board has exactly one solution.
Clarifying questions
What you would ask an interviewer before writing any code.