Sudoku Solver
Master this topic with zero to advance depth.
Sudoku Solver
The Sudoku Logic
Sudoku is a constraint satisfaction problem. A valid solution must have the digits 1-9 exactly once in every row, column, and subgrid.
Backtracking Search
We find an empty cell, try placing a digit from 1-9, and if it's valid, move to the next empty cell. If no digit works, we backtrack to the previous cell and try the next possible digit.
State Representation
Instead of searching the board to validate, we can use boolean matrices or bitmasks to track which numbers are present in each row, column, and box.
Solve a Sudoku puzzle using backtracking. Includes visual constraint check trace.
Examples
Level I: Basic Backtracking
Intuition
Try every number in every empty cell.
Iterate through cells. For each '.', try numbers 1-9. Check if the number is valid in the current row, column, and box by scanning the board.
Detailed Dry Run
Dry Run Trace:
| Cell | Value | Validity Check (R, C, B) | Action |
| :---: | :---: | :----------------------- | :----- |
| (0,2) | '4' | [â, â, â] | Recurse|
| (0,3) | '1' | [â Row Conflict] | Try 2 |
| (0,3) | '6' | [â, â, â] | Recurse|Level II: Optimized Backtracking (State Tracking with Bitmasks)
Intuition
Use bitmasks to mark digits used in rows, columns, and boxes for validation.
Maintain rows[9], cols[9], and boxes[9] as integers. rows[i] & (1 << digit) tells us if digit is already in row i. This replaces the isValid check with bitwise .
Detailed Dry Run
To check if '5' can be placed at (0, 2):
Check: (rows[0] | cols[2] | boxes[0]) & (1 << 5) == 0.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.