Home
DSA Course
Backtracking
Sudoku Solver
Sudoku Solver
Solve a 9x9 Sudoku board by filling empty cells such that every row, column, and 3x3 box contains digits 1-9.
Sudoku Solver
Ready
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.Intuition
Imagine trying to solve a Sudoku puzzle. You find an empty cell and try '1'. If it works, you move to the next. If you get stuck later, you erase '1' and try '2'.
This 'try and undo' process is Backtracking. We systematically explore valid numbers for each empty cell.
Concept
Key Concepts:
- Backtracking: A depth-first search where we build a solution piece by piece and abandon a path ('backtrack') if it violates constraints.
- Constraints: A number is valid if it's not already in the same Row, Column, or 3x3 Sub-box.
- Recursion: We solve for one cell, then recursively solve for the rest.
How it Works
- Find the first empty cell (marked '.' or 0).
- Try digits 1 through 9.
- Check if the digit is valid (not in row, col, box).
- If valid, place it and recurse to solve the rest of the board.
- If recursion returns true, we found a solution!
- If recursion returns false, reset the cell (backtrack) and try the next digit.
Step-by-Step Breakdown
Example: Empty cell at (0, 2)
- Try '1': Valid? No (exists in row).
- Try '2': Valid? Yes. Place '2'.
- Recurse to (0, 3).
- ... If path fails, return to (0, 2), reset '2', try '3'.
When to Use
- Constraint Satisfaction Problems (Sudoku, N-Queens, Crossword).
- Finding one valid configuration among exponentially many options.
When NOT to Use
- When an optimization or greedy approach exists (e.g., Shortest Path).
- When the search space is too large for brute-force recursion.
How to Identify
"Find a valid arrangement", "Fill the grid", "Satisfy constraints".
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
