Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
1-9 must occur exactly once in each row.1-9 must occur exactly once in each column.1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.The '.' character indicates empty cells.
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: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] Explanation: The input board is shown above and the only valid solution is shown below:![]()
Constraints:
board.length == 9board[i].length == 9board[i][j] is a digit or '.'.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a Sudoku puzzle with several empty spots waiting to be filled with numbers. The brute force approach involves trying every single possible number in every empty spot until you find a combination that follows all the puzzle rules.
Here's how the algorithm would work step-by-step:
class Solution:
def solveSudoku(self, board: list[list[str]]) -> None:
def is_valid_placement(current_row, current_column, current_digit):
string_digit = str(current_digit)
for row_index in range(9):
if board[row_index][current_column] == string_digit:
return False
if board[current_row][row_index] == string_digit:
return False
box_row = 3 * (current_row // 3) + row_index // 3
box_col = 3 * (current_column // 3) + row_index % 3
if board[box_row][box_col] == string_digit:
return False
return True
def backtrack_sudoku():
# Scan the entire grid to locate the next unassigned cell for exploration
for row_index in range(9):
for column_index in range(9):
if board[row_index][column_index] == '.':
for candidate_digit in range(1, 10):
if is_valid_placement(row_index, column_index, candidate_digit):
board[row_index][column_index] = str(candidate_digit)
# Recurse deeper to check if this valid branch leads to a complete solution
if backtrack_sudoku():
return True
# Backtrack by undoing the choice if the path leads to an invalid dead end
board[row_index][column_index] = '.'
return False
return True
backtrack_sudoku()The optimal strategy to solve the puzzle is a method of careful trial and error combined with logical deduction. Instead of randomly guessing numbers everywhere, we search for the next empty space, try a valid number, and move forward, stepping back to change our choice only if we hit a dead end.
Here's how the algorithm would work step-by-step:
class Solution:
def solveSudoku(self, board: list[list[str]]) -> None:
def is_valid_placement(current_board, row_index, col_index, candidate_char):
box_start_row = 3 * (row_index // 3)
box_start_col = 3 * (col_index // 3)
for iterator in range(9):
if current_board[row_index][iterator] == candidate_char:
return False
if current_board[iterator][col_index] == candidate_char:
return False
row_offset = box_start_row + (iterator // 3)
col_offset = box_start_col + (iterator % 3)
if current_board[row_offset][col_offset] == candidate_char:
return False
return True
def backtrack_solve(current_board):
# Scan the board to find the next available empty spot that needs a number.
for row_index in range(9):
for col_index in range(9):
if current_board[row_index][col_index] == '.':
for candidate_digit in '123456789':
if is_valid_placement(current_board, row_index, col_index, candidate_digit):
current_board[row_index][col_index] = candidate_digit
# Assume current placement is correct and proceed to fill subsequent spots.
if backtrack_solve(current_board):
return True
current_board[row_index][col_index] = '.'
# Backtrack if no valid number works here, allowing previous choices to change.
return False
return True
backtrack_solve(board)| Case | How to Handle |
|---|---|
| Null or empty board input | Check for null or incorrect dimensions at the start and return immediately without crashing |
| Board with no valid solution | The backtracking algorithm will exhaust all possibilities and return false, leaving the board in a valid state or signaling failure |
| Board with multiple valid solutions | The recursive search will return true upon finding the first valid completion, effectively stopping and returning that solution |
| Board already completely solved | The algorithm will find no empty cells and immediately return true without making any unnecessary changes |
| Invalid initial board with pre-existing rule violations | Validation checks prior to placement will instantly reject conflicting numbers and trigger backtracking or failure |
| Deep recursion stack overflow on complex puzzles | Since the board size is fixed at 9x9, the maximum recursion depth is strictly bounded by 81, preventing stack overflow |